<?php
/*
+--------------------------------------------------------------------------
|   Web: http://www.enbac.com 
|   Started date : 30/06/2008
+---------------------------------------------------------------------------
|   > Script written by Nova
+---------------------------------------------------------------------------
*/

if (eregi(basename( __FILE__ ), $_SERVER['PHP_SELF'])) {
	print "<h1>Incorrect access</h1>You cannot access this file directly.";
	exit();
}

class ajax_personal {
	function playme(){
		$code = AZLib::getParam('code');

		switch( $code ){
			case 'password':
				$this->check_password();
				break;				
			case 'edit_user':
				$this->edit_user();
				break;
			case 'check_user_compose':
				$this->fn_check_user_compose();
				break;		
			case 'get_avatar_ya':
				$this->fn_get_avatar_ya();
				break;				
			case 'schedule_up':
				$this->schedule_up();
				break;
			case 'show_edit_up_item':
				$this->schedule_up_item_form();
				break;	
			case 'get_schedule_config':
				$this->get_schedule_config();
				break;	
			case 'set_schedule_up':
				$this->set_schedule_up();
				break;	
			case 'setup_item_up_auto':
				$this->setup_item_up_auto();
				break;								
			case 'show_log_up_item':
				$this->show_log_up_item();
				break;
			case 'send_mess':
				$this->send_mess();
				break;	
			case "fwMess":
			case "rpMess":
				$this->fwrpMess();
				break;		
			case 'show_mes_inbox':			
				$this->show_mes_inbox();
				break;
			case 'show_mes_outbox':			
				$this->show_mes_outbox();
				break;	
			case 'show_detail_mess':
				$this->fn_show_detail_mes();
				break;	
			case 'delmess':			
				$this->delmess();
				break;
			case 'change_password':			
				$this->change_password();
				break;
			case 'show_all_notify':			
				$this->show_all_notify();
				break;
			case 'update_notify_read':
				$this->update_notify_read();
				break;
            case 'update_blast':
				$this->update_blast();
				break;
			default:
				$this->home();
				break;
		}
}
	
	function home(){
		global $display;
		die("Nothing to do...");
	}

        function update_blast(){
            $user_id=$_REQUEST['user_id'];
            $blast = $_REQUEST['blast'];
            DB::query("UPDATE user SET blast='$blast' WHERE id=$user_id");
            User::getUser($user_id,0,1);
            echo "done!";
            exit;
        }

	function show_all_notify()
	{
		global $display;
		AZLib::getCats();
		$feed_follows 	= array();//hoạt động của các thành viên mà mình theo đuôi
		$follow_ids 	= '';//hoạt động của các thành viên mà mình theo đuôi
		
		$action 		= Url::get('action');
		$num_per_page 	= 20;
		
		$ajax_mod  		= (int)(Url::get('act')=='shop_giaodich');
		
		$page_no 	= 1;
		$cur_group 	= 0;
		
		$all_feeds 	  = array();//Lưu mảng tất cả các cập nhật
		$all_feed_ars = array();//mảng các cập nhật đã đc sắp xếp, xử lý
		
		$user_arr  	  = array();//Mảng các user
		$item_arr  	  = array();//Mảng các Giao dịch
		$entry_arr    = array();//Mảng các Bài viết
		
		$item_ids_ar  = array();//Mảng id các Giao dịch
		$user_ids_ar  = array();//Mảng id các user
		$entry_ids_ar = array();//Mảng id các Bài viết
		
		$item_comment_ids 	= "";//Id các phản hồi giao dịch
		$item_comment_arr 	= array();//các phản hồi giao dịch
		
		$user_comment_ids 	= "";//Id các lưu bút
		$user_comment_arr 	= array();//các lưu bút
		
		$pm_ids 			= "";//Id các tin nhắn
		$pm_arr 			= array();//các tin nhắn
		
		$entry_comment_ids 	= "";//Id các bài viết
		$entry_comment_arr  = array();//các bài viết
		
		$this->show_more  	= false;//các bài viết
		
		$where = "WHERE user_id = ".User::id();
		$limit = " LIMIT ".($num_per_page*($page_no-1)).",".($num_per_page+1);
		
		$where .= " AND type IN(1,2,3,4,5,6)";
		
		
		$total_unread = 0;
		
		$sql = "SELECT * FROM feed $where ORDER BY time DESC $limit";
		$re = DB::query($sql);
		$stt= 0;
		if($re){	
			while($feed = mysql_fetch_assoc($re)){
				if($stt<$num_per_page){
					if($feed['type']==1 || $feed['type']==2){
						$item_comment_ids.=($item_comment_ids!=''?',':'').$feed['ref_id'];
						
						if(!in_array($feed['item_id'],$item_ids_ar)){
							$item_ids_ar[$feed['item_id']]=$feed['item_id'];
						}
					}
					elseif($feed['type']==3){
						$user_comment_ids.=($user_comment_ids!=''?',':'').$feed['ref_id'];
					}
					elseif($feed['type']==4){
						$pm_ids.=($pm_ids!=''?',':'').$feed['ref_id'];
					}
					elseif($feed['type']==5 || $feed['type']==6){
						$entry_comment_ids.=($entry_comment_ids!=''?',':'').$feed['ref_id'];
						
						if($feed['item_id'])
						$entry_ids_ar[$feed['item_id']]=$feed['item_id'];
					}
					
					if($feed['act_user_id'] && !in_array($feed['act_user_id'],$user_ids_ar)){
						$user_ids_ar[$feed['act_user_id']]=$feed['act_user_id'];
					}
					
					$all_feeds[$feed['id']] = $feed;
					$stt++;
				}else{
					$this->show_more = true;
				}
			}
		}
			
		if($item_ids_ar){
			$item_ids=implode(',',$item_ids_ar);
			
			if($item_ids!=''){
				$re = DB::query("SELECT  id, name ,up_time, status, state, currency_id, category_id, img_server, img_url AS image_url FROM item WHERE id IN($item_ids)");
				if($re){
					while($item = mysql_fetch_assoc($re)){
						
						if(isset(CGlobal::$allCategories[$item['category_id']])){
							$item['link_view'] = Url::build('item_detail',array('id'=>$item['id'],'ebname'=>AZLib::safe_title($item['name']),'nice_name'=>CGlobal::$allCategories[$item['category_id']]['nice_name']));
						}
						else{	
							$item['link_view'] = Url::build('item_detail',array('id'=>$item['id'],'ebname'=>AZLib::safe_title($item['name'])));
						}
						if(!$item['status']) $total_unread++;
						
						$item_arr[$item['id']]=$item;
					}
				}
			}
		}
		
		if(!empty($entry_ids_ar)){
			$entry_ids=implode(',',$entry_ids_ar);
			
			if($entry_ids!=''){
				$re = DB::query("SELECT id, title, status, user_name, time_modify, image_url FROM user_entry WHERE id IN($entry_ids)");
				if($re){
					while($entry = mysql_fetch_assoc($re)){
						$entry['link_view'] = WEB_DIR.AZRewrite::formatUrl('?page=user_entry&user_name='.$entry['user_name'].'&cmd_entry=view&entry_id='.$entry['id'].'&ebname='.AZLib::safe_title($entry['title']));
						if(!$entry['status']) $total_unread++;
						$entry_arr[$entry['id']] = $entry;
					}
				}
			}
		}
		
		
		if($user_ids_ar){
			$user_ids=implode(',',$user_ids_ar);
			
			if($user_ids!=''){
				$re = DB::query("SELECT id, user_name, blast, avatar_url,img_server FROM user WHERE id IN($user_ids)");
				if($re){
					while ($user = mysql_fetch_assoc($re)){
						if($user['avatar_url']){
							$user['avatar_url']= 'http://'.CGlobal::$img_server[$user['img_server']].'thumb/50_50/'.$user['avatar_url'];
						}
						else{
							$user['avatar_url'] = 'style/images/54x54.gif';
						}
						
						$user_arr[$user['id']]=$user;
					}
				}
			}
		}
		
		
		//Phản hồi giao dịch
		if($item_comment_ids!=''){
			$re = DB::query("SELECT * FROM comment WHERE id IN($item_comment_ids)");
			if($re){
				while ($comment = mysql_fetch_assoc($re)){
					$comment['content']   = AZLib::parseBBCode(stripslashes($comment['content']));
					$comment['s_content'] = AZLib::plainText($comment['content']);
						
					if(strlen($comment['s_content'])>20){
						$comment['s_content'] = AZLib::word_limit($comment['s_content'],10,'..');
					}
					$comment['time'] 	= AZLib::duration_time($comment['time']);
					if(!$comment['status']) $total_unread++;
					$item_comment_arr[$comment['id']] = $comment;
				}
			}
		}
		
		//Lưu bút
		if($user_comment_ids!=''){
			$re = DB::query("SELECT * FROM comment_user WHERE id IN($user_comment_ids)");
			if($re){
				while ($comment = mysql_fetch_assoc($re)){
					$comment['content']   = AZLib::parseBBCode(stripslashes($comment['content']));
					$comment['s_content'] = AZLib::plainText($comment['content']);
						
					if(strlen($comment['s_content'])>20){
						$comment['s_content'] = AZLib::word_limit($comment['s_content'],10,'..');
					}
					$comment['time'] 	= AZLib::duration_time($comment['time']);
					if(!$comment['status']) $total_unread++;
					$user_comment_arr[$comment['id']] = $comment;
				}
			}
		}
		
		if($pm_ids!='' && $pm_ids!=0){
			//Tin nhắn
			$re = DB::query("SELECT mt.*, msg.msg_post as content FROM (SELECT mt_id AS id, mt_msg_id, mt_title, mt_ref_id , mt_from_id AS sender_user_id, mt_date AS time, mt_read AS status FROM message_topics WHERE mt_id IN($pm_ids)) AS mt LEFT JOIN message_text AS msg ON mt.mt_msg_id = msg.msg_id");
			if($re){
				while ($comment = mysql_fetch_assoc($re)){
					$comment['content']   = AZLib::parseBBCode(stripslashes($comment['content']));
					$comment['s_content'] = AZLib::plainText($comment['content']);
						
					if(strlen($comment['s_content'])>20){
						$comment['s_content'] = AZLib::word_limit($comment['s_content'],10,'..');
					}
					
					$comment['time'] 		= AZLib::duration_time($comment['time']);
					if(!$comment['status']) $total_unread++;
					$pm_arr[$comment['id']] = $comment;
				}
			}
		}
		
		if($entry_comment_ids!=''){//Phản hồi bài viết
			$re = DB::query("SELECT id, entry_id, content, time, sender_user_id, sender_user_name, sender_email, status FROM user_entry_comment WHERE id IN($entry_comment_ids)");
					
			if($re){
				while ($comment = mysql_fetch_assoc($re)){
					$comment['content']   = AZLib::parseBBCode(stripslashes($comment['content']));
					$comment['s_content'] = AZLib::plainText($comment['content']);
						
					if(strlen($comment['s_content'])>20){
						$comment['s_content'] = AZLib::word_limit($comment['s_content'],10,'..');
					}
					
					$comment['time'] 	= AZLib::duration_time($comment['time']);
					if(!$comment['status']) $total_unread++;
					$entry_comment_arr[$comment['id']] = $comment;
				}
			}
		}
		
		$item_ids_ar	=array();//Mảng item_id cập nhật bỏ qua cho các feed chủ thể tương ứng khi giao dịch bị xoá hoặc khoá!
		$item_ids_ar2	=array();//Mảng item_id cập nhật bỏ qua cho các feed khách thể tương ứng khi giao dịch bị xoá hoặc khoá!
		$entry_ids_ar	=array();
		$entry_ids_ar2 	=array();
		
		$c_user_ids_ar  =array();
		$pm_ids_ar 		=array();
		
		$unread_feed_ids= '';
		$del_feed_ids 	= '';
		
		
		
		if($all_feeds){
			foreach ($all_feeds as $feed){
				if($feed['type']==4){//Tin nhắn
					if(isset($user_arr[$feed['act_user_id']])){
						$feed['sender_user_name'] = $user_arr[$feed['act_user_id']]['user_name'];
					}
					else{
						$feed['sender_user_name'] = '';
					}
				}
				
				if($feed['type']==1 || $feed['type']==2){//Phản hồi giao dịch hoặc Trả lời phản hồi giao dịch
					if(isset($item_comment_arr[$feed['ref_id']])){
						$feed['item_id'] 				= $item_comment_arr[$feed['ref_id']]['item_id'];																		
						$feed['content'] 				= $item_comment_arr[$feed['ref_id']]['content'];
						$feed['s_content'] 				= $item_comment_arr[$feed['ref_id']]['s_content'];
						$feed['time'] 					= $item_comment_arr[$feed['ref_id']]['time'];
						$feed['sender_user_id'] 		= $item_comment_arr[$feed['ref_id']]['sender_user_id'];
						$feed['sender_user_name'] 		= $item_comment_arr[$feed['ref_id']]['sender_user_name'];
						$feed['sender_email'] 			= $item_comment_arr[$feed['ref_id']]['sender_email'];
						
						$status							= $feed['status'];
						if($feed['type']==1)
							$feed['status'] 			= $item_comment_arr[$feed['ref_id']]['status'];
						else
							$feed['status'] 			= $item_comment_arr[$feed['ref_id']]['replied_status'];
						
						if($feed['status']==0||$status==0){
							$unread_feed_ids.=($unread_feed_ids!=''?',':'').$feed['id'];
							
							if($feed['type']==1 && $feed['status']==0){//Mảng item_id cập nhật bỏ qua cho các feed chủ thể tương ứng khi giao dịch bị xoá hoặc khoá!
								$item_ids_ar[$feed['item_id']]=$feed['item_id'];
							}
							elseif($feed['type']==2 && $feed['status']==0){//Mảng item_id cập nhật bỏ qua cho các feed khách thể tương ứng khi giao dịch bị xoá hoặc khoá!
								$item_ids_ar2[$feed['item_id']] = $feed['item_id'];
							}
						}
						
						if(isset($item_arr[$feed['item_id']]) && $item_arr[$feed['item_id']]['state']==0 && $item_arr[$feed['item_id']]['status']!=-1){
							$feed['item'] = $item_arr[$feed['item_id']];
							$all_feed_ars[$feed['id']] = $feed;
						}
						else{
							$del_feed_ids.=($del_feed_ids!=''?',':'').$feed['id'];
						}
					}
					else{
						$del_feed_ids.=($del_feed_ids!=''?',':'').$feed['id'];
					}
				}
				elseif($feed['type']==3){//Lưu bút
					if(isset($user_comment_arr[$feed['ref_id']])){
						$feed['content'] 				= $user_comment_arr[$feed['ref_id']]['content'];
						$feed['s_content'] 				= $user_comment_arr[$feed['ref_id']]['s_content'];
						$feed['time'] 					= $user_comment_arr[$feed['ref_id']]['time'];
						$feed['sender_user_id'] 		= $user_comment_arr[$feed['ref_id']]['sender_user_id'];
						$feed['sender_user_name'] 		= $user_comment_arr[$feed['ref_id']]['sender_user_name'];
						
						$status							= $feed['status'];
						
						$feed['status'] 				= $user_comment_arr[$feed['ref_id']]['status'];
						if($feed['status']==0||$status==0){
							$unread_feed_ids.=($unread_feed_ids!=''?',':'').$feed['id'];
						
							if($feed['status']==0){//
								$c_user_ids_ar[$feed['ref_id']]=$feed['ref_id'];
							}
						}
						
						$all_feed_ars[$feed['id']] 		= $feed;
					}
					else{
						$del_feed_ids.=($del_feed_ids!=''?',':'').$feed['id'];
					}
				}
				elseif($feed['type']==4){//Tin nhắn
					
					if(isset($pm_arr[$feed['ref_id']])){
						$feed['content'] 				= $pm_arr[$feed['ref_id']]['content'];
						$feed['s_content'] 				= $pm_arr[$feed['ref_id']]['s_content'];
						$feed['time'] 					= $pm_arr[$feed['ref_id']]['time'];
						$feed['sender_user_id'] 		= $pm_arr[$feed['ref_id']]['sender_user_id'];
						$feed['mt_title'] 				= $pm_arr[$feed['ref_id']]['mt_title'];
						$id = $pm_arr[$feed['ref_id']]['mt_ref_id']?$pm_arr[$feed['ref_id']]['mt_ref_id']:$pm_arr[$feed['ref_id']]['id'];
						$feed['mt_title_link']			= "message.html#inbox/$id";
						
						
						$status							= $feed['status'];
						$feed['status'] 				= $pm_arr[$feed['ref_id']]['status'];
						
						
						if($feed['status']==0||$status==0){
							$unread_feed_ids.=($unread_feed_ids!=''?',':'').$feed['id'];
							
							if($feed['status']==0){//
								$pm_ids_ar[$feed['ref_id']]=$feed['ref_id'];
							}
						}
						
						$all_feed_ars[$feed['id']] = $feed;
					}
					else{
						$del_feed_ids.=($del_feed_ids!=''?',':'').$feed['id'];
					}
				}
				elseif($feed['type']==5 || $feed['type']==6){//Phản hồi Bài viết
					if(isset($entry_comment_arr[$feed['ref_id']])){
						$feed['entry_id'] 			= $entry_comment_arr[$feed['ref_id']]['entry_id'];
						$feed['content'] 			= $entry_comment_arr[$feed['ref_id']]['content'];
						$feed['s_content'] 			= $entry_comment_arr[$feed['ref_id']]['s_content'];
						$feed['time'] 				= $entry_comment_arr[$feed['ref_id']]['time'];
						$feed['sender_user_id'] 		= $entry_comment_arr[$feed['ref_id']]['sender_user_id'];
						$feed['sender_user_name'] 		= $entry_comment_arr[$feed['ref_id']]['sender_user_name'];
						$feed['sender_email'] 			= $entry_comment_arr[$feed['ref_id']]['sender_email'];
						
						$status							= $feed['status'];
						if($feed['type']==5)
							$feed['status'] 				= $entry_comment_arr[$feed['ref_id']]['status'];
						else
							$feed['status'] 				= $entry_comment_arr[$feed['ref_id']]['replied_status'];
						
						if($feed['status']==0||$status==0){
							$unread_feed_ids.=($unread_feed_ids!=''?',':'').$feed['id'];
						
							if($feed['type']==5 && $feed['status']==0){//Mảng entrry_id cập nhật bỏ qua cho các feed chủ thể tương ứng khi giao dịch bị xoá hoặc khoá!
								$entry_ids_ar[$feed['entry_id']] = $feed['entry_id'];
							}
							if($feed['type']==6 && $feed['status']==0){//Mảng entrry_id cập nhật bỏ qua cho các feed khách thể tương ứng khi giao dịch bị xoá hoặc khoá!
								$entry_ids_ar2[$feed['entry_id']]=$feed['entry_id'];
							}
						}
						
						if(isset($entry_arr[$feed['entry_id']])){
							$feed['entry'] = $entry_arr[$feed['entry_id']];
							
							$all_feed_ars[$feed['id']] = $feed;
						}
						else{
							$del_feed_ids.=($del_feed_ids!=''?',':'').$feed['id'];
						}
					}
					else{
						$del_feed_ids.=($del_feed_ids!=''?',':'').$feed['id'];
					}
				}
			}
		}
		
		$display->add('all_feed_ars',$all_feed_ars);
		
		$display->add('image_path', 'http://'.IMAGE_PATH);
		
		$display->add('get_page',  AZNet::$page['name']);
		$display->add('get_cmd',   Url::get('cmd','office'));
		$display->add('get_act',   $action);
		$display->add('user_name', User::user_name());
		
		$this->total_group 	= count($all_feed_ars);
		
		$display->add('total_group',$this->total_group);
		$display->add('cur_group',$cur_group);
		$display->add('show_more',$this->show_more);
		
		$display->add('cur_user_name',User::user_name());
		$display->add('more_notify',WEB_DIR.AZRewrite::formatUrl('?page=personal'));
		$transact_office = $display->output('tbl_notify_ajax',true,'Personal');
		
		$display->add('transact_office',$transact_office);
		
		$display->add('total_comment_user',	User::$current->data['total_comment_user']);
		$display->add('total_new_comment',	User::$current->data['total_new_comment']);
		$display->add('total_pm',			User::$current->data['total_pm']);
		
		$display->add('can_edit_blast',((User::is_admin()) || !User::is_block()));
		$blast			= User::$current->data['blast'];
		$avatar_link 	= '';
		$avatar_url 	= 'style/images/no_avatar_item.gif';
			
		if(User::$current->data['avatar_url'] != ''){
			$avatar_link 	= "http://".CGlobal::$img_server[User::$current->data['img_server']].User::$current->data['avatar_url'];
			$avatar_url 	= AZLib::getImageThumb(User::$current->data['avatar_url'],80,80,0,User::$current->data['img_server']);
		}
		
		if($blast == ''){
			$blast = '...';
		}
		else{
			$blast = ' '.$blast;
			if(strpos($blast,'http://')){
				$user_blast = $blast;
				while(strpos($user_blast,'http://')){
					$tmp = substr($user_blast,strpos($user_blast,'http://'));
					
					if(strpos($tmp,' ') || strpos($tmp,'<')){
						if(strpos($tmp,' ') && strpos($tmp,'<') && (strpos($tmp,' ') > strpos($tmp,'<'))){
							$blast_url = substr($tmp,0,strpos($tmp,'<'));
						}
						else{
							$blast_url = substr($tmp,0,strpos($tmp,' '));
						}
					}
					else{
						$blast_url = $tmp;
					}
					$user_blast = str_replace($blast_url,'',$user_blast);
				}
				$new_blast_url = ' <a rel="nofollow" href="'.$blast_url.'" target="_blank">Click here</a>';
				$blast = substr($user_blast.$new_blast_url,1);
			}
		}
		
		$display->add('avatar_link',$avatar_link);
		$display->add('avatar_url',$avatar_url);
		$display->add('blast',$blast);
		$display->add('user_id',User::id());
		
		//Cập nhật sách theo đuôi
		
		if(isset($user_arr[$feed['act_user_id']]) && $user_arr[$feed['act_user_id']]['avatar_url']){
			$feed['avatar_url'] = $user_arr[$feed['act_user_id']]['avatar_url'];
		}
		else{
			$feed['avatar_url'] = 'style/images/54x54.gif';
		}
				
			
		if($feed_follows){
			$tmp_feed_follows	= $feed_follows;
			$feed_follows 		= array();
			
			foreach($tmp_feed_follows as $feed){
				if(isset($user_arr[$feed['user_id']])){
					if($user_arr[$feed['user_id']]['avatar_url']){
						$avatar_url = $user_arr[$feed['user_id']]['avatar_url'];
					}
					else{
						$avatar_url = 'style/images/54x54.gif';
					}
					
					$user_name 		= $user_arr[$feed['user_id']]['user_name'];
					
					if($feed['type'] ==7){//entry
						if(isset($entry_arr[$feed['item_id']])){
							$feed_follows[$feed['user_id']]['user_name'] 	= $user_name;
							$feed_follows[$feed['user_id']]['avatar_url'] 	= $avatar_url;
					
							$feed['entry_name'] = $entry_arr[$feed['item_id']]['title'];
							$feed['entry_link'] = WEB_DIR.AZRewrite::formatUrl('?page=user_entry&user_name='.$user_name.'&cmd_entry=view&entry_id='.$feed['item_id'].'&ebname='.AZLib::safe_title($feed['entry_name']));
							$feed['time'] 		= date('H:i d/m/Y',$feed['time']);
							
							$feed_follows[$feed['user_id']]['feeds'][$feed['id']] 	= $feed;
						}
					}
					else{
						$feed_follows[$feed['user_id']]['user_name'] 	= $user_name;
						$feed_follows[$feed['user_id']]['avatar_url'] 	= $avatar_url;
						
						$feed['blast'] = $user_arr[$feed['user_id']]['blast'];
						$feed['time'] 		= date('H:i d/m/Y',$feed['time']);
						
						$feed_follows[$feed['user_id']]['feeds'][$feed['id']] = $feed;
					}
				}
			}
		}
		
		$json = array();
		$active_notify = array();
		$active_notify['item_ids_ar'] = $item_ids_ar;
		$active_notify['item_ids_ar2'] = $item_ids_ar2;
		$active_notify['c_user_ids_ar'] = $c_user_ids_ar;
		$active_notify['pm_ids_ar'] = $pm_ids_ar;
		
		$json['active_notify'] = $active_notify;
		$json['total_unread'] = $total_unread;
		$json['total_notify'] = User::$current->data['total_comment_user'] + User::$current->data['total_new_comment'] + User::$current->data['total_pm'];
		$json['content'] = $display->output('tb_notify',true,'Personal');
		echo json_encode($json);
		exit;
	}
	
	function update_notify_read()
	{
		$total_new_comment  = 0;
		$total_comment_user = 0;
		$total_pm		  	= 0;
		
		$item_ids_ar = Url::get('item_ids_ar','');
		$item_ids_ar2 = Url::get('item_ids_ar2','');
		$c_user_ids_ar = Url::get('c_user_ids_ar','');
		$pm_ids_ar = Url::get('pm_ids_ar','');
		
		if($item_ids_ar){//Mảng item_id cập nhật bỏ qua cho các feed chủ thể tương ứng khi giao dịch bị xoá hoặc khoá!
			$item_ids = explode(',',$item_ids_ar);
			DB::query("UPDATE comment SET status=1 WHERE item_id IN($item_ids_ar)");			
			$total_new_comment-= count($item_ids);
		}
		
		if($item_ids_ar2){//Mảng item_id cập nhật bỏ qua cho các feed khách thể tương ứng khi giao dịch bị xoá hoặc khoá!
			$item_ids = explode(',',$item_ids_ar2);
			DB::query("UPDATE comment SET replied_status=1 WHERE item_id IN($item_ids_ar2)");
			
			$total_new_comment+= count($item_ids);
		}
		
		if($c_user_ids_ar){
			$u_user_ids = explode(',',$c_user_ids_ar);
			DB::query("UPDATE comment_user SET status=1 WHERE id IN($c_user_ids_ar)");
			
			$total_comment_user+= count($u_user_ids);
		}	
		if($pm_ids_ar){
			$pm_ids = explode(',',$pm_ids_ar);

			DB::query("UPDATE message_topics SET mt_read=1 WHERE mt_id IN($pm_ids_ar)");
			
			$total_pm+= count($pm_ids);
		}
		if($unread_feed_ids!='' && $unread_feed_ids!=0){
			DB::query("UPDATE feed SET status=1 WHERE id IN($unread_feed_ids)");
		}
		
		if($total_new_comment || $total_comment_user || $total_pm){
			$update_sql="";
			
			if($item_comment_ids)
			{
				//$total_new_comment 	= User::$current->data['total_new_comment'] - $total_new_comment;
				//$total_new_comment 	= DB::fetch("SELECT count(*) AS total_feed FROM feed WHERE user_id = ".User::id()." AND type IN(1,2) AND status=0 AND time>".(TIME_NOW-15*24*3600),'total_feed',0);
				//$total_new_comment 		= DB::fetch("SELECT count(*) AS total_feed FROM comment WHERE receiver_user_id = ".User::id()." AND mt_read=0 AND mt_vid_folder='inbox' AND mt_date>".(TIME_NOW-15*24*3600),'total_feed',0);
				//$update_sql.="total_new_comment=$total_new_comment";
				$total_new_comment = 0;
				$update_sql.="total_new_comment=$total_new_comment";
			}
			
			if($total_comment_user)
			{
				//$total_comment_user 	= User::$current->data['total_comment_user'] - $total_comment_user;
				//$total_comment_user 	= DB::fetch("SELECT count(*) AS total_feed FROM feed WHERE user_id = ".User::id()." AND type = 3 AND status=0 AND time>".(TIME_NOW-15*24*3600),'total_feed',0);
				$total_comment_user 	= DB::fetch("SELECT count(*) AS total_feed FROM comment_user WHERE receiver_user_id = ".User::id()." AND status=0 AND sender_user_id != ".User::id()." AND time>".(TIME_NOW-15*24*3600),'total_feed',0);
				$update_sql.=($update_sql!=''?', ':'')."total_comment_user=$total_comment_user";
			}
			
			if($total_pm)
			{
				//$total_pm 			= User::$current->data['total_pm'] - $total_pm;
				//$total_pm 				= DB::fetch("SELECT count(*) AS total_feed FROM feed WHERE user_id = ".User::id()." AND type = 4 AND status=0 AND time>".(TIME_NOW-15*24*3600),'total_feed',0);
				$total_pm 				= DB::fetch("SELECT count(*) AS total_feed FROM message_topics WHERE mt_owner_id = ".User::id()." AND mt_read=0 AND mt_vid_folder='inbox' AND mt_date>".(TIME_NOW-15*24*3600),'total_feed',0);
				
				$update_sql.=($update_sql!=''?', ':'')."total_pm=$total_pm";
			}
			
			if($update_sql!=''){
				DB::query("UPDATE user SET $update_sql WHERE id=".User::id());
				if(MEMCACHE_ON){
					$user_memcache = AZMemcache::do_get("user:".User::id());
					if($user_memcache){
						$user_memcache['total_new_comment']  = (int)$total_new_comment;
						$user_memcache['total_comment_user'] = (int)$total_comment_user;
						$user_memcache['total_pm'] 			 = (int)$total_pm;
						
						AZMemcache::do_put("user:".User::id(),$user_memcache);
					}
				}
				else{
					User::getUser(User::id(),0,1);
				}
			}
		}
		echo 'success';
		exit;
	}
	
	function check_password(){
		if(isset($_REQUEST['old_password']) && User::is_login()){
			$password = $_REQUEST['old_password'];
			$sql = "select id from user where password = '".User::encode_password($password)."' and id='".User::id()."'";
			DB::query($sql);
			if(DB::num_rows()){
				$resp = 'true';
			}
		    else{
				$resp = 'false';
			}
			 
			echo $resp;
			exit();
		}
		else{
			echo "no_login";		
			exit();
		}
	}
	
	function edit_user(){
		$file_name 		= strtolower($_FILES['avatar_url']['name']);
		
		$upload_path  		= AZLib::folderUpload(User::id() ,'avatar');
		
		$max_upload_file_size 	= 2*1024*1024;
		$file_ext 		= AZLib::getExtension($file_name);
		$new_path 		= '';	
		
		if($file_name && in_array($file_ext,array('.jpg','.jpeg','.gif','.png')) && filesize($_FILES['avatar_url']['tmp_name'])< $max_upload_file_size){
			if(AZLib::ftp_check_dir($upload_path)){
				$old_avatar_url = Url::get('old_avatar_url');
				if($old_avatar_url <> ''){
					@AZLib::ftp_image_delete_file($old_avatar_url);
				}
				$new_path   = $upload_path.date("YmdHis",TIME_NOW) . '_'.substr(AZLib::make_safe_name(basename($file_name,$file_ext)),0,36).$file_ext;	
			
				@AZLib::ftp_image_put_file($new_path,$_FILES['avatar_url']['tmp_name']);
			}
		}	
		
		$show_email  = Url::get('show_email');
		$email_alert = Url::get('email_alert');
		
		$new_blast = Url::get('blast');
		
		if(AZLib::checkBadWord($new_blast)){
			$new_blast = '';
		}
		$new_sign = Url::get('sign');
		
		if(AZLib::checkBadWord($new_sign))
		{
			$new_sign = '';
		}
		$full_name = Url::get('full_name');
		if(AZLib::checkBadWord($full_name))
		{
			$full_name = '';
		}
		$address = Url::get('address');
		if(AZLib::checkBadWord($address))
		{
			$address = '';
		}
		$home_phone = Url::get('home_phone');
		if(AZLib::checkBadWord($home_phone))
		{
			$home_phone = '';
		}
		$fax = Url::get('fax');
		if(AZLib::checkBadWord($fax))
		{
			$fax = '';
		}
		$mobile_phone = Url::get('mobile_phone');
		if(AZLib::checkBadWord($mobile_phone))
		{
			$mobile_phone = '';
		}
		
		$website = Url::get('website');
		if(AZLib::checkBadWord($website))
		{
			$website = '';
		}
		$yahoo_id = Url::get('yahoo_id');
		if(AZLib::checkBadWord($yahoo_id))
		{
			$yahoo_id = '';
		}
		$skype_id = Url::get('skype_id');
		if(AZLib::checkBadWord($skype_id))
		{
			$skype_id = '';
		}
		
		$arr = explode('-',Url::get('birth_day'));
		if(is_numeric($arr['0']) && is_numeric($arr['1']) && is_numeric($arr['2']))
		{
			$strBirthDay = $arr['2'].'-'.$arr['1'].'-'.$arr['0'];
		}
		else
		{
			$strBirthDay = "";
		}
		
		$new_row=array	(
						'full_name'=>$full_name,
						'address'=>$address,						
						'birth_day'=>$strBirthDay,
						'home_phone'=>$home_phone,
						'fax'=>$fax,
						'mobile_phone'=>$mobile_phone,
						'show_email'=>$show_email,
						'email_alert'=>$email_alert,
						'website'=>$website,					
						'yahoo_id'=>$yahoo_id,
						'skype_id'=>$skype_id,
						'blast'=>$new_blast,
						'signature'=>$new_sign,
						'avatar_url'=>$new_path
					);
		$id_new_row = DB::update('user',$new_row,'id="'.User::id().'"');
		@User::updateUserCache(User::id());
		if($id_new_row)
		{
			echo "success";
			exit();
		}
		else 
		{
			echo "unsuccess";
			exit();
		}
		
	}
	
	function fn_check_user_compose(){
		if(isset($_REQUEST['receiver']) && User::is_login()){
			$receiver = $_REQUEST['receiver'];
			$sql = "SELECT id FROM user WHERE user_name = '".$receiver."'";
			DB::query($sql);
			if(DB::num_rows()){
				$resp = 'true';
			}
		    else{
				$resp = 'false';
			}
			 
			echo $resp;
			exit();
		}
		else{
			echo "no_login";		
			exit();
		}
	}
	
	function fn_show_detail_mes(){
		if(!User::is_login()){
			echo 'no_login';	
			exit();
		}
		global $display;
		$is_archive 	= Url::get('is_archive',0);
		$boxType 		= Url::get('boxType','inbox');
		$table_topics 	= 'message_topics';
		$table_text 	= 'message_text';
		$url_cmd 		= '';
		$url_archive 	= '';
		
		if($is_archive){
			$table_topics = $table_topics.'_archive';
			$table_text = $table_text.'_archive';
			$url_cmd = '?cmd=archive';
			$url_archive = '&is_archive=1';
		}
		
		$content = '';
		$mt_id = AZLib::getParam('mt_id');		
		if($mt_id){
			$sql = 'SELECT	'.$table_text.'.msg_id,'.$table_text.'.msg_author_id,'.$table_text.'.msg_author_name, '.$table_text.'.msg_date, '.$table_text.'.msg_post, '.
						$table_topics.'.mt_id, '.$table_topics.'.mt_title, '.$table_topics.'.mt_vid_folder, '.$table_topics.'.mt_from_id, '.
						$table_topics.'.mt_owner_id, '.$table_topics.'.mt_owner_name,	'.$table_topics.'.mt_read, '.$table_topics.'.mt_to_name, 
						user.avatar_url, user.img_server, user.signature 
					FROM '.$table_text.', '.$table_topics.', user	
					WHERE '.$table_text.'.msg_id  = '.$table_topics.'.mt_msg_id 
						AND ('.$table_topics.'.mt_ref_id = ' . $mt_id . ' OR '.$table_topics.'.mt_id = ' . $mt_id . ')
						AND user.id = '.$table_text.'.msg_author_id 
						AND '.$table_topics.'.mt_owner_id = ' . User::id() . '
					ORDER BY msg_date ASC';
			//echo $sql;		
			
			$resultMsg 		= DB::query($sql);
			$update_read 	= 0;
			
			$old_messages 		= array();
			$message_details 	= array();
			
			if($resultMsg)
			{
				$total = mysql_num_rows($resultMsg);
				$row_number = 0;
				
				while($message = mysql_fetch_assoc($resultMsg))
				{
					$row_number++;
					if($row_number == 1)
					{
						$title = $message['mt_title'];
						
						
						$display->add('mt_title',$title);
						$display->add('total',$total);
						
						if(User::id() != $message['mt_from_id']){
							$user_name = $message['mt_to_name'];
						}
						else
						{
							$user_name = $message['mt_owner_name'];
						}
						
						$display->add('user_id',User::id());
						$display->add('mt_from_id',$message['mt_from_id']);
						
						$display->add('user_name',$user_name);
					}
					
					if($message['msg_author_id'] != User::id())
					{
						$message['usernameClass'] = 'class="guest"';
					}
					
					if($message['avatar_url']){
						$message['avatar_url'] = AZLib::getImageThumb($message['avatar_url'],50,50,0,$message['img_server']);
					}
					else{
						$message['avatar_url'] = "style/images/50x50.gif";				
					}
					
					$message['msg_post'] = preg_replace( "/\n/", "<br />", $message['msg_post']);
					$message['msg_post'] = AZLib::parseBBCode(AZLib::convert_one_br($message['msg_post']));
					$message['msg_post'] = $this->process_description($message['msg_post']);
					$msg_date = date('H:i | ',$message['msg_date']);
					if(date('d.m.y',$message['msg_date']) == date('d.m.y',TIME_NOW)){
						$msg_date.= '<font color="green">H&#244;m nay</font>';
					}
					else{
						$msg_date.= date('d.m.y',$message['msg_date']);										
					}
					
					$message['msg_date'] = $msg_date;	
	
					// Nếu có bất cứ tin nhắn nào trong luồng chưa được đọc, đặt cờ cập nhật trạng thái đã đọc = 1
					if(!$message['mt_read']&&!$update_read){
						$update_read = 1;
					}
					
					if($total > 3 && $row_number < ($total - 2)){
						$old_messages[] = $message;
					}
					else{
						$message_details[] = $message;
					}
				}
			}
			
			$display->add('old_messages',$old_messages);
			$display->add('message_details',$message_details);
			
			
			$display->add('boxType',$boxType);
			$display->add('url_cmd',$url_cmd);
			$display->add('mt_id',$mt_id);
			
			//cap nhat so lan tin nhan moi
			//if($update_read && $items['mt_vid_folder'] == 'inbox'){
			if($update_read){
				DB::query("UPDATE $table_topics SET mt_read=1 WHERE (mt_ref_id=$mt_id AND mt_owner_id = " . User::id() . " AND mt_read = 0) OR mt_id=$mt_id");
				//DB::query('UPDATE '.$table_topics.' SET mt_read=1 WHERE mt_id="'.$mt_id.'"');		
				
				$condition = 'mt_owner_id =' .User::id() . ' AND mt_vid_folder = "inbox" AND mt_read = 0';
				$rows_total = DB::count('message_topics',$condition);
				DB::query("UPDATE user SET total_pm  = " . $rows_total . " WHERE id = ".User::id());
				
				//Cập nhật đã đọc - trả lời cho feed
				DB::query("UPDATE feed SET status = 1 WHERE ref_id = $mt_id AND type=4");
				User::getUser(User::id(),0,1);
			}
		}	
	
		$display->output("Detail",0,"ManageMessage");
		echo $content;
		
		System::halt();	
	}
	
	function fn_get_avatar_ya(){
		$avatar_id = Url::get('yahoo_id');
		
		if(!User::is_login()){
			echo 'not_login';
			exit();
		}
		elseif($avatar_id==''){
			echo "empty";
			exit();
		}
		else{	
			if(User::is_block()){		
				echo "unsuccess";
				exit();
			}
			
			if(User::$current->data['avatar_url']!=''){
				@AZLib::ftp_image_delete_file(User::$current->data['avatar_url']);
			}
			
			$avatar_url = AZLib::get_yahoo_avatar($avatar_id,User::id(),IMAGE_SERVER_NO);
			
			if(DB::query('UPDATE user SET avatar_url="'.$avatar_url.'", img_server='.IMAGE_SERVER_NO.' WHERE id="'.User::id().'"')){			
				User::updateUserCache(User::id());
				echo '<img src="'.AZLib::getImageThumb($avatar_url,100,100,0,IMAGE_SERVER_NO).'" />';
				exit();
			}
			else{
				echo "unsuccess";
				exit();
			}
		}
	}
	
	
	
	function schedule_up(){
		if(!User::is_login()){
			echo 'not_login';
			exit();
		}
		
		$item_id = (int)Url::get('item_id');
		$status  = (int)Url::get('status');//0:tat,1:bat
				
		if($status == 0 || ($status == 1 && (User::$current->data['up_item']>0 || User::is_az_team() || User::level() > 0))){
			if($item_id>0 && !User::is_block()){
				$item 			= Item::get_item($item_id);
				$item_memcache 	= $item;
					
				if($item && $item['user_id']==User::id()){
					
					if($status){//Lên lịch
						if(!User::have_permit(ADMIN_UPTIN)){
							$s_total = DB::fetch("SELECT COUNT(*) AS s_total FROM (SELECT item_id FROM up_item_schedule WHERE user_id=".$item['user_id']." GROUP BY item_id)  AS uis",'s_total',0);
						}
						else
							$s_total = 0;
						
						if($s_total<5){
							if(!$item["is_up_auto"]){//Chưa lên lịch
								$s_status=0;
								if($item["status"]==-1 || $item["status"]==0 || $item["status"]==2 || $item["status"]==3){
									$s_status = 3;
								}
								
								$new_row=array	(
													'user_id'		=>$item['user_id'],
													'user_name'		=>$item['user_name'],
													'item_id'		=>$item['id'],
													'des'			=>$item['name'],
													'time_add'		=>TIME_NOW,
													'time_modify'	=>TIME_NOW,
													'run_order'		=>'1',
													'up_per_day'	=>'3',	
													'week_day'		=>'0|0|0|0|0|0|0',
													'time_run'		=>'',
													'time_next_run'	=>TIME_NOW,
													'up_remain'		=>0,
													'up_total'		=>0,
													'status'		=>$s_status
												);
								$id = DB::insert('up_item_schedule',$new_row);
								$new_row=array	(
													'user_id'		=>$item['user_id'],
													'user_name'		=>$item['user_name'],
													'item_id'		=>$item['id'],
													'des'			=>$item['name'],
													'time_add'		=>TIME_NOW,
													'time_modify'	=>TIME_NOW,
													'run_order'		=>'2',
													'up_per_day'	=>'3',	
													'week_day'		=>'0|0|0|0|0|0|0',
													'time_run'		=>'',
													'time_next_run'	=>TIME_NOW,
													'up_remain'		=>0,
													'up_total'		=>0,
													'status'		=>$s_status
												);
												
								$id = DB::insert('up_item_schedule',$new_row);
								$new_row=array	(
													'user_id'		=>$item['user_id'],
													'user_name'		=>$item['user_name'],
													'item_id'		=>$item['id'],
													'des'			=>$item['name'],
													'time_add'		=>TIME_NOW,
													'time_modify'	=>TIME_NOW,
													'run_order'		=>'3',
													'up_per_day'	=>'3',	
													'week_day'		=>'0|0|0|0|0|0|0',
													'time_run'		=>'',
													'time_next_run'	=>TIME_NOW,
													'up_remain'		=>0,
													'up_total'		=>0,
													'status'		=>$s_status
												);
								
								$id = DB::insert('up_item_schedule',$new_row);
								
								if($id){
									DB::query("UPDATE item SET is_up_auto = 1 WHERE id= $item_id");
									if(MEMCACHE_ON){
										$item_memcache['is_up_auto'] = 1;
										AZMemcache::do_put("item:$item_id",$item_memcache);
									}
								}
							}
						}
						else{
							echo "limit";
							exit;
						}
					}
					else{//Xoá lịch
						$s_row=DB::select('up_item_schedule',"item_id=$item_id ORDER BY up_remain DESC");
						
						if($s_row){
							DB::delete('up_item_schedule',"item_id=$item_id");
							
							if($s_row['up_remain']>0){
								DB::query("UPDATE user SET up_item=up_item+".(int)$s_row['up_remain']." WHERE id=".$item['user_id']);
								User::getUser($item['user_id'],0,1);
							}
						}
						
						if($item["is_up_auto"]){
							DB::query("UPDATE item SET is_up_auto = 0 WHERE id= $item_id");
							
							if(MEMCACHE_ON){
								$item_memcache['is_up_auto'] = 0;
								AZMemcache::do_put("item:$item_id",$item_memcache);
							}
						}
					}
					
					echo "success";
					exit();	
				}
			}
		}
		echo "not_success";
		exit;
	}
	function schedule_up_item_form(){
		$item_id = (int)Url::get('item_id',0);
		//if(User::is_az_team() || User::level()>0)
		{
			if($item_id>0 && User::is_login() && !User::is_block()){	
				$user 	 =array();
				$item 	 =array();
				$up_item =array();
				$up_items=array();
				$user	 =array();
				
				$re = DB::query("SELECT * FROM up_item_schedule WHERE item_id=$item_id ORDER BY run_order");
				
				if($re){
					while ($s_item = mysql_fetch_assoc($re)) {
						$up_items[]=$s_item;
					}
				}
				
				if(!$up_items){
					echo "not_exist";
					exit;
				}
				
				$item 			= Item::get_item($item_id);
				$item_memcache 	= $item;
					
				if($item && $item['status']!=-1){
					if(User::id() == $item['user_id']){
						$user 	 = DB::select('user',"id={$item['user_id']}");
						$up_item = $up_items[0];
						
						foreach ($up_items as $u_item){
							if($u_item['up_remain']>$up_item['up_remain']){
								$up_item['up_remain']=$u_item['up_remain'];
							}
						}
						
						if($up_item['up_remain']<0){
							$up_item['up_remain'] = 0;
						}
						
						global $display;
						//$run_times=array();
						$run_times='';
						foreach ($up_items as $run_time){
							if($run_time['time_run']){
								$arr=explode('-',$run_time['time_run']);
								
								$run_hour 	= $arr[0];
								$run_min 	= $arr[1];
								$run_times.=$arr[0].':'.$arr[1].'|';
							}
						}
						
						$display->add('run_times', substr($run_times,0,-1));
						
						if($up_item['week_day']){
							$arr=explode('|',$up_item['week_day']);
							if($arr){
								foreach ($arr as $stt=>$val){
									$stt+=2;
									$display->add("week_day$stt",$val);
								}
							}
						}
						
						$display->add('up_remain',		(int)$up_item['up_remain']);
						$display->add('status',			(int)$up_item['status']);
						
						$display->add('item_id',		(int)$item['id']);
						
						$display->add('user_up_count',	$user['up_item']);
						
						$display->add('item_name',		stripslashes($item['name']));
						$display->add('user_name',		$item['user_name']);
						$display->add('item_url',		"?page=item_detail&id={$item['id']}&ebname=".AZLib::safe_title($item['name']));
						
						$display->add('cur_up_per_day',	count($up_items));
						
						$display->output('UpTin',false,"Personal");
							
						exit;
					}
				}
				else{//delete schedule here...
					DB::query("UPDATE up_item_schedule SET status=3 WHERE item_id=$item_id");
					echo "item_not_exist";
					exit;
				}
			}
		}
		
		echo 'invalid';
		exit();	 	 
	}
	
	function get_schedule_config()
	{
		$data = array('msg'=>'');
		
		if(User::is_login())
		{
			$item_id = (int)Url::get('item_id',0);
		
			if($item_id>0 && !User::is_block() && (User::is_az_team() || User::level()>0))
			{
				$user 	 =array();
				$item 	 =array();
				$up_item =array();
				$up_items=array();
				$user	 =array();
				
				$item 			= Item::get_item($item_id);
				$item_memcache 	= $item;
					
				if($item && $item['status']!=-1)
				{
					if(User::id() == $item['user_id'])
					{
						$re = DB::query("SELECT * FROM up_item_schedule WHERE item_id=$item_id ORDER BY run_order");
				
						if($re){
							while ($s_item = mysql_fetch_assoc($re)){
								$up_items[]=$s_item;
							}
						}
						
						$user 	 = DB::select('user',"id={$item['user_id']}");
						
						global $display;
						$run_times='';
						
						if($up_items)
						{
							$up_item 	= $up_items[0];
						
							foreach ($up_items as $u_item)
							{
								if($u_item['up_remain']>$up_item['up_remain']){
									$up_item['up_remain']=$u_item['up_remain'];
								}
							}
							
							if($up_item['up_remain']<0)
							{
								$up_item['up_remain'] = 0;
							}
							
							if($up_item['week_day'])
							{
								$arr=explode('|',$up_item['week_day']);
								if($arr){
									foreach ($arr as $stt=>$val){
										$stt+=2;
										$display->add("week_day$stt",$val);
									}
								}
							}
							
							foreach ($up_items as $run_time)
							{
								if($run_time['time_run'])
								{
									$arr=explode('-',$run_time['time_run']);
									
									$run_hour 	= $arr[0];
									$run_min 	= $arr[1];
									
									$run_times.= ($run_times != ''? '|' : '').$arr[0].':'.$arr[1];
								}
							}
							
							$display->add('up_remain',		(int)$up_item['up_remain']);
							$display->add('status',			(int)$up_item['status']);
							
							$display->add('del_up',			1);
						}
						else 
						{
							$display->add('up_remain',		0);
							$display->add('status',			0);
						}
						
						$display->add('item_id',		(int)$item['id']);
						$display->add('reload_page',	(int)Url::get('reload_page'));
						
						$display->add('user_up_count',	$user['up_item']);
						
						$display->add('item_name',		stripslashes($item['name']));
						$display->add('user_name',		$item['user_name']);
						$display->add('item_url',		"p{$item['id']}/".AZLib::safe_title($item['name']).".html");
						
						$data['html'] 		= $display->output('ScheduleConfig',1,"Personal");
						$data['run_times'] 	= $run_times;
						
						echo json_encode($data);
						exit;
					}
				}
				else{//delete schedule here...
					DB::query("UPDATE up_item_schedule SET status=3 WHERE item_id=$item_id");
					
					$data['msg'] = 'item_not_exist';
					echo json_encode($data);
					exit;
				}
			}
		}
		else 
		{
			$data['msg'] = 'not_login';
			echo json_encode($data);
			exit;
		}
		
		$data['msg'] = 'no_perm';
		echo json_encode($data);
		exit;	 	 
	}
	
	function set_schedule_up()
	{
		$item_id = (int)Url::get('item_id',0);
		
		$response=array();
		
		if($item_id>0 && User::is_login() && !User::is_block())
		{		
			$user 	 	=array();
			$item 	 	=array();
			$up_item 	=array();
			$up_items	=array();
			$user	 	=array();
			
			$item 		= Item::get_item($item_id);
			
			if($item && $item['status'] != -1)
			{
				$response['item_id'] 		= $item_id;
				$response['reload_page'] 	= (int)Url::get('reload_page',0);
				
				if(User::id() == $item['user_id'])
				{
					$up_rows	=	array();//Bản ghi up lịch
					
					$user 	 	= 	DB::select('user',"id={$item['user_id']}");
					
					$re = DB::query("SELECT * FROM up_item_schedule WHERE item_id=$item_id ORDER BY run_order");
			
					if($re){
						while ($s_item = mysql_fetch_assoc($re))
						{
							$up_rows[]=$s_item;
						}
					}
					
					if($up_rows)
					{
						$up_exist 	= 	true;
						
						$up_item = $up_rows[0];
					
						foreach ($up_rows as $u_item){
							if($u_item['up_remain']>$up_item['up_remain']){
								$up_item['up_remain']=$u_item['up_remain'];
							}
						}
						
						if($up_item['up_remain']<0)
						{
							$up_item['up_remain'] = 0;
						}
					}
					else
					{
						$up_exist 	= 	false;
						$up_item 	= array("up_remain"=>0,"time_add" => TIME_NOW);
						
						/*$response['msg'] = "not_exist";
						
						echo json_encode($response);
						exit;*/
					}
					
					##################################################################################
					#Ngày up trong tuần
					$week_day_arr	= Url::get('week_day');
					
					if($week_day_arr)
					{
						$week_day_tmp	= array(
													2=>0,
													3=>0,
													4=>0,
													5=>0,
													6=>0,
													7=>0,
													8=>0,
												);
											
						foreach ($week_day_arr as $wday=>$val)
						{
							if(isset($week_day_tmp[$wday]))
							{
								$week_day_tmp[$wday]=(int)(bool)$val;
							}
						}
						
						$week_day = implode('|',$week_day_tmp);
					}
					else{
						$response['msg'] = "choose_wday";
						
						echo json_encode($response);//'Bạn phải chọn ngày up trong tuần!'
						exit;
					}
					##################################################################################
					
					
					##################################################################################
					#Thời điểm up mỗi ngày
					
					$string_up_time = Url::get('string_up_time');
					
					if($string_up_time != '')
					{
						$arr_time 		= explode('|',$string_up_time);
						
						$run_hours 		= array();//Giờ từng lượt up
						$run_mins 		= array();//Phút từng lượt up
						$time_temp 		= array();//Thời điểm up tính từ mốc 0 của thời gian
	
						foreach ($arr_time as $value)
						{
							$arr_temp 	= explode(':',$value);
							
							$uTime 		= mktime($arr_temp[0],$arr_temp[1],0,0,0,0);
							$complain 	= false;
							
							/*foreach ($time_temp as $time_val)
							{
								if ($uTime == $time_val)
								{
									$complain = true;
								}
								else
								{
									$complain = false;
								}
							}
							if(!$complain)
							{
								$time_temp[] = $uTime;
							}	
							*/
							
							if(!in_array($uTime,$time_temp))
							{
								$time_temp[] = $uTime;//Cho vào mảng thời điểm up tạm
							}
						}
						sort($time_temp);//Sắp xếp thứ tự
						
						foreach ($time_temp as $val)
						{
							$run_hours[]	= date('H',$val);
							$run_mins[] 	= date('i',$val);
						}
						##################################################################################
						
						$up_remain		=(int)Url::get('up_remain',0);//Tổng số lần up cho cả lịch up
						
						if($up_remain<0)
						{
							$up_remain = 0;
						}
						
						$run_times		=array();
						$last_time		= 0 ;
						
						$i			=	1;
						$first_time	=	1;//lần up đầu tiên
						
						if($run_hours)
						{
							$wday_now = date('N',time())-1;
							
							foreach ($run_hours as $stt=>$hour)
							{
								if(isset($run_mins[$stt]))
								{
									$cur_time = mktime($hour,$run_mins[$stt],0,date('m',TIME_NOW),date('d',TIME_NOW),date('Y',TIME_NOW));
	
									if($last_time)
									{
										if($cur_time <= $last_time+899)//Thời điểm up hiện tại phải muộn hơn thời điểm up trước ít nhất 15 phút
										{
											continue;//Bỏ qua
											/*$response['msg'] 	= "run_hour_error";
											$response['alert'] 	= "Thời gian lượt up thứ $i phải muộn hơn lần up thứ ".($i-1)." ít nhất 15 phút!";
	
											echo json_encode($response);
											exit;*/
										}
									}
									
									$last_time 	= $cur_time;
									
									$arr		=explode('|',$week_day);
									$wday_up  	= $wday_now;
									
									//Tính thời gian up kế tiếp của bản ghi
									$time_next_run = $cur_time;
									
									if($time_next_run <= TIME_NOW+5  || !isset($arr[$wday_up]) || (isset($arr[$wday_up]) && !$arr[$wday_up]))
									{
										$first_time++;
										//$wday_up = $wday_now;
										$w_temp=$wday_up++;
										
										while ($wday_up<7)
										{
											if(isset($arr[$wday_up]) && $arr[$wday_up]){
												$time_next_run = $cur_time + 86400*($wday_up-$wday_now);
												
												if($time_next_run>(TIME_NOW+5))//nếu thời gian up kế tiếp lớn hơn thời gian hiện tại + 5 giây
												break;
											}
											$wday_up++;
										}
										
										if(!isset($arr[$wday_up]) || (isset($arr[$wday_up]) && !$arr[$wday_up])){
											$wday_up = 0;
											//while ($wday_up<7){
											while ($wday_up<$w_temp)
											{
												if(isset($arr[$wday_up]) && $arr[$wday_up])
												{
													$time_next_run = $cur_time + 86400*(7-$wday_now + $wday_up);
													
													if($time_next_run>(TIME_NOW+5))//nếu thời gian up kế tiếp lớn hơn thời gian hiện tại + 5 giây
													break;
												}
												$wday_up++;
											}	
										}
									}
									
									$run_times[] = array(
														'time_run'		=>str_pad($hour, 2, "0", STR_PAD_LEFT).'-'.str_pad($run_mins[$stt], 2, "0", STR_PAD_LEFT),
														'time_next_run'	=>$time_next_run,
														);
									$i++;
								}
							}
						}
						
						if($run_times)
						{
							$up_per_day = count($run_times);
							
							foreach ($run_times as $stt=>$time)
							{
								$stt++;
								
								$up_items[]	=array(
													'run_order'		=>$stt,
													'time_run' 		=>$time['time_run'],
													'time_next_run' =>$time['time_next_run'],
													);
							}	
						}
						else
						{
							$response['msg'] 	= "run_hour";
							
							echo json_encode($response);//'Bạn phải chọn ít nhất 1 lần up / ngày!'
							exit;
						}
						
						if($first_time	>	$up_per_day)
						{
							$first_time	=	1;
						}
						
						$up_item['status']	= (int)Url::get('status',0);//0:tat,1:bat
						
						if($up_remain<=0)
						{
							$response['msg'] 	= "up_zero";
						
							echo json_encode($response);//Chưa nhập lượt up
							exit;
						}
						
						if($up_item['up_remain']	!=	$up_remain )//Nếu tổng số lượt up của lịch thay đổi => cập nhật vào cho tài khoản
						{
							if( ($user['up_item'] + $up_item['up_remain']) < $up_remain){//Tài khoản ko đủ để tăng tổng số lượt up sẽ dùng cho tin
								$up_remain 	= $user['up_item']+$up_item['up_remain'];
								
								if($up_remain<=0)
								{
									$response['msg'] 	= "up_over";
								
									echo json_encode($response);//Chưa nhập lượt up
									exit;
								}
							}
							
							$user_up_remain 	= $user['up_item'] + $up_item['up_remain'] - $up_remain;
							
							if($user_up_remain<0)
							$user_up_remain = 0;
							
							DB::query("UPDATE user SET up_item=$user_up_remain WHERE id=".$user['id']);
							User::getUser($user['id'],0,1);
						}
				
						if($up_item['status'] && $up_remain<=0){
							$status = 2;
						}
						elseif($item["status"]==-1 || $item["status"]==0 || $item["status"]==2 || $item["status"]==3){
							$status = 3;
						}
						else{
							$status	= $up_item['status'];
						}
						#############################################################################
						#Cập nhật cho tin
						if($item['is_up_auto'] != 1) 
						{
							DB::query("UPDATE item SET is_up_auto = 1 WHERE id= $item_id");
							
							if(MEMCACHE_ON)
							{
								$item['is_up_auto'] = 1;
								AZMemcache::do_put("item:$item_id",$item);
							}
						}
						#############################################################################
						
						
						$del_ids = '';
						$add_sql = '';
						
						$up_total 				= $up_remain;
						$up_item['up_remain']	= $up_remain;
						
						if($up_items)
						{
							foreach ($up_items as $key=>$u_item)
							{
								if($u_item['run_order']<$first_time)
								{
									$up_remain = $up_total - ($up_per_day-$first_time) - $u_item['run_order'];
								}
								else{
									$up_remain = $up_total - ($u_item['run_order']-$first_time);
								}
								
								if(isset($up_rows[$key]))
								{
									DB::update('up_item_schedule',array(
														'user_id'	 	=>$user['id'],
														'user_name'	 	=>$user['user_name'],
														'item_id'	 	=>$item['id'],
														'des'		 	=>$item['name'],
														'time_modify'	=>TIME_NOW,
														'run_order'	 	=>$u_item['run_order'],
														'up_per_day'	=>$up_per_day,
														'week_day'		=>$week_day,
														'time_run'		=>$u_item['time_run'],
														'time_next_run'	=>$u_item['time_next_run'],
														'up_remain'	 	=>$up_remain,
														'up_total'	 	=>$up_total,
														'status'	 	=>$status,
														),"id={$up_rows[$key]['id']}");
														
									unset($up_rows[$key]);
								}
								else
								{
									//$add_sql="INSERT INTO up_item_schedule (user_id,user_name,item_id,des,time_add,time_modify,run_order,week_day,time_run,time_next_run,up_remain,up_total,status) VALUES ".$add_sql;
									$add_sql.=($add_sql?",\n":"")."({$user['id']},'{$user['user_name']}',{$item['id']},
																	'{$item['name']}',{$up_item['time_add']},".TIME_NOW.",{$u_item['run_order']},$up_per_day,
																	'$week_day','{$u_item['time_run']}',{$u_item['time_next_run']},
																	$up_remain,$up_total,$status)";
								}
							}
						}
						
						if($up_rows){
							foreach ($up_rows as $u_item){
								$del_ids.=($del_ids?',':'').$u_item['id'];
							}
						}
						
						if($add_sql){
							$add_sql="INSERT INTO up_item_schedule (user_id,user_name,item_id,des,time_add,time_modify,run_order,up_per_day,week_day,time_run,time_next_run,up_remain,up_total,status) VALUES ".$add_sql;
							DB::query($add_sql);
						}
						if($del_ids){
							DB::delete("up_item_schedule","id IN($del_ids)");
						}
						
						$response['msg'] = "success";
						echo json_encode($response);
						exit;
					}
					else
					{
						$response['msg'] 	= "run_hour";
						
						echo json_encode($response);//'Bạn phải chọn ít nhất 1 lần up / ngày!'
						exit;
					}
				}
			}
			else{//delete schedule here...
				DB::query("UPDATE up_item_schedule SET status=3 WHERE item_id=$item_id");
				echo "item_not_exist";
				exit;
			}
		}
		$response['msg'] = "invalid";
		echo json_encode($response);
		exit;
	}
	
	function setup_item_up_auto()
	{
		$item_id = (int)Url::get('item_id',0);
		
		$response=array();
		
		if($item_id>0 && User::is_login() && !User::is_block()){		
			$user 	 =array();
			$item 	 =array();
			$up_item =array();
			$up_rows=array();
			$up_items=array();
			$user	 =array();
			
			$re = DB::query("SELECT * FROM up_item_schedule WHERE item_id=$item_id ORDER BY run_order");
			
			if($re){
				while ($s_item = mysql_fetch_assoc($re)) {
					$up_rows[]=$s_item;
				}
			}
			
			if(!$up_rows){
				$response['msg'] = "not_exist";
				
				echo json_encode($response);
				exit;
			}
			
			$item 			= Item::get_item($item_id);
			
			if($item && $item['status']!=-1){
				if(User::id() == $item['user_id']){
					$user 	 = DB::select('user',"id={$item['user_id']}");
					$up_item = $up_rows[0];
					
					foreach ($up_rows as $u_item){
						if($u_item['up_remain']>$up_item['up_remain']){
							$up_item['up_remain']=$u_item['up_remain'];
						}
					}
					
					if($up_item['up_remain']<0){
						$up_item['up_remain'] = 0;
					}
					$string_up_time = Url::get('string_up_time');
					$arr_time = explode('|',$string_up_time);
					$run_hours = array();
					$run_mins = array();
					$time_temp = array();
					//$i = 0;
					foreach ($arr_time as $value){
						$arr_temp = explode(':',$value);
						//print_r($value);
						$uTime = mktime($arr_temp[0],$arr_temp[1],0,0,0,0);
						$complain = false;
						foreach ($time_temp as $time_val)
						{
							//echo $uTime.'==>'.$time_val.'<br>';
							if ($uTime == $time_val)
							{
								$complain = true;
							}
							else
							{
								$complain = false;
							}
						}
						if(!$complain)
						{
							$time_temp[] = $uTime;
						}
						//$run_hours[]= $arr_temp[0];
						//$run_mins[] = $arr_temp[1];
						//$i++;										
					}
					sort($time_temp);
					foreach ($time_temp as $val)
					{
						$run_hours[]= date('H',$val);
						$run_mins[] = date('i',$val);
					}
					//print_r ($time_temp);
					//exit();
					//unset($arr_temp);
					
					//$run_hours 		= Url::get('run_hour');
					//$run_mins 		= Url::get('run_min');
					
					
					$up_remain		=(int)Url::get('up_remain',0);
					if($up_remain<0){
						$up_remain = 0;
					}
					
					$run_times		=array();
					$last_time		= 0 ;
					
					$week_day_arr	= Url::get('week_day');
					$week_day_tmp	= array(
											2=>0,
											3=>0,
											4=>0,
											5=>0,
											6=>0,
											7=>0,
											8=>0,
											);
					
					if($week_day_arr){
						foreach ($week_day_arr as $wday=>$val){
							if(isset($week_day_tmp[$wday])){
								$week_day_tmp[$wday]=(int)(bool)$val;
							}
						}
					}
					else{
						$response['msg'] = "choose_wday";
						echo json_encode($response);//'Bạn phải chọn ngày up trong tuần!'
						exit;
					}
					
					$week_day = implode('|',$week_day_tmp);
					
					$i=1;
					$first_time=1;//lần up đầu tiên
					if($run_hours){
						$wday_now = date('N',time())-1;
						
						foreach ($run_hours as $stt=>$hour){
							if($stt>=0 && $hour>=0 && $hour<24 && isset($run_mins[$stt]) && $run_mins[$stt]>=0 && $run_mins[$stt]<60){
								$cur_time = mktime($hour,$run_mins[$stt],0,date('m'),date('d'),date('Y'));
								if($last_time){
									if($cur_time<=$last_time+899){
										$response['msg'] = "run_hour_error";
										$response['alert'] = "Thời gian lượt up thứ $i phải muộn hơn lần up thứ ".($i-1)." ít nhất 15 phút!";
										echo json_encode($response);
										exit;
									}
								}
								
								$last_time = $cur_time;
								
								
								$arr=explode('|',$week_day);
								$wday_up  = $wday_now;
								
								//Tính thời gian up kế tiếp của bản ghi
								$time_next_run = $cur_time;
								
								if($time_next_run<=TIME_NOW+5 || !isset($arr[$wday_up]) || (isset($arr[$wday_up]) && !$arr[$wday_up])){			
									$first_time++;
									//$wday_up = $wday_now;
									$w_temp=$wday_up++;
									
									while ($wday_up<7){																		
										if(isset($arr[$wday_up]) && $arr[$wday_up]){
											$time_next_run = $cur_time + 86400*($wday_up-$wday_now);
											
											if($time_next_run>(TIME_NOW+5))//nếu thời gian up kế tiếp lớn hơn thời gian hiện tại + 5 giây
											break;
										}
										$wday_up++;
									}
									
									if(!isset($arr[$wday_up]) || (isset($arr[$wday_up]) && !$arr[$wday_up])){
										$wday_up = 0;
										//while ($wday_up<7){
										while ($wday_up<$w_temp){
											if(isset($arr[$wday_up]) && $arr[$wday_up]){
												$time_next_run = $cur_time + 86400*(7-$wday_now + $wday_up);
												
												if($time_next_run>(TIME_NOW+5))//nếu thời gian up kế tiếp lớn hơn thời gian hiện tại + 5 giây
												break;
											}
											$wday_up++;
										}	
									}
								}
								
								$run_times[] = array(
													'time_run'		=>str_pad($hour, 2, "0", STR_PAD_LEFT).'-'.str_pad($run_mins[$stt], 2, "0", STR_PAD_LEFT),
													'time_next_run'	=>$time_next_run,
													);
								$i++;
							}
						}
					}
					
					if($run_times){
						$up_per_day = count($run_times);
						foreach ($run_times as $stt=>$time){
							$stt++;
							
							$up_items[]=array(
											'run_order'		=>$stt,
											'time_run' 		=>$time['time_run'],
											'time_next_run' =>$time['time_next_run'],
											);
						}	
					}
					else{
						$up_per_day = 0;
						$response['msg'] = "run_hour";
						echo json_encode($response);//'Bạn phải chọn ít nhất 1 lần up / ngày!'
						exit;
					}
					
					if($first_time>$up_per_day)
					$first_time=1;
					
					$up_item['status']	= (int)Url::get('status',0);//0:tat,1:bat
					
					if($up_item['up_remain']!=$up_remain ){
						if( ($user['up_item'] + $up_item['up_remain']) < $up_remain){//Tăng số lượt up
							$up_remain 	= $user['up_item']+$up_item['up_remain'];
						}
						
						$user_up_remain 	= $user['up_item'] + $up_item['up_remain'] - $up_remain;
						
						if($user_up_remain<0)
						$user_up_remain = 0;
						
						DB::query("UPDATE user SET up_item=$user_up_remain WHERE id=".$user['id']);
						User::getUser($user['id'],0,1);
					}
			
					if($up_item['status'] && $up_remain<=0){
						$status = 2;
					}
					elseif($item["status"]==-1 || $item["status"]==0 || $item["status"]==2 || $item["status"]==3){
						$status = 3;
					}
					else{
						$status	= $up_item['status'];
					}
					
					$del_ids = '';
					$add_sql = '';
					
					$up_total = $up_remain;
					$up_item['up_remain']	= $up_remain;
					
					if($up_items){
						foreach ($up_items as $key=>$u_item){
							if($u_item['run_order']<$first_time){
								$up_remain = $up_total - ($up_per_day-$first_time) - $u_item['run_order'];
							}
							else{
								$up_remain = $up_total - ($u_item['run_order']-$first_time);
							}
							
							if(isset($up_rows[$key])){
								DB::update('up_item_schedule',array(
													'user_id'	 	=>$user['id'],
													'user_name'	 	=>$user['user_name'],
													'item_id'	 	=>$item['id'],
													'des'		 	=>$item['name'],
													'time_modify'	=>TIME_NOW,
													'run_order'	 	=>$u_item['run_order'],
													'up_per_day'	=>$up_per_day,
													'week_day'		=>$week_day,
													'time_run'		=>$u_item['time_run'],
													'time_next_run'	=>$u_item['time_next_run'],
													'up_remain'	 	=>$up_remain,
													'up_total'	 	=>$up_total,
													'status'	 	=>$status,
													),"id={$up_rows[$key]['id']}");
													
								unset($up_rows[$key]);
							}
							else{
								//$add_sql="INSERT INTO up_item_schedule (user_id,user_name,item_id,des,time_add,time_modify,run_order,week_day,time_run,time_next_run,up_remain,up_total,status) VALUES ".$add_sql;
								$add_sql.=($add_sql?",\n":"")."({$user['id']},'{$user['user_name']}',{$item['id']},
																'{$item['name']}',{$up_item['time_add']},".TIME_NOW.",{$u_item['run_order']},$up_per_day,
																'$week_day','{$u_item['time_run']}',{$u_item['time_next_run']},
																$up_remain,$up_total,$status)";
							}
						}
					}
					
					if($up_rows){
						foreach ($up_rows as $u_item){
							$del_ids.=($del_ids?',':'').$u_item['id'];
						}
					}
					
					if($add_sql){
						$add_sql="INSERT INTO up_item_schedule (user_id,user_name,item_id,des,time_add,time_modify,run_order,up_per_day,week_day,time_run,time_next_run,up_remain,up_total,status) VALUES ".$add_sql;
						DB::query($add_sql);
					}
					if($del_ids){
						DB::delete("up_item_schedule","id IN($del_ids)");
					}
					
					$response['msg'] = "success";
					echo json_encode($response);
					exit;
				}
			}
			else{//delete schedule here...
				DB::query("UPDATE up_item_schedule SET status=3 WHERE item_id=$item_id");
				echo "item_not_exist";
				exit;
			}
		}
		$response['msg'] = "invalid";
		echo json_encode($response);
		exit;
	}
	
	function show_log_up_item(){
		$item_id = (int)Url::get('item_id',0);
		
		if($item_id>0 && User::is_login() && !User::is_block()){	
			$log_ups 		= array();
			$item 			= Item::get_item($item_id);
				
			if($item){
				if(User::id() == $item['user_id']){
					global $display;
					
					$re = DB::query("SELECT * FROM up_item_log WHERE item_id=$item_id ORDER BY id DESC LIMIT 200");
			
					if($re){
						$stt = 1;
						while ($log_up = mysql_fetch_assoc($re)) {
							$log_up['stt']=$stt++;
							
							$log_up['up_time']=date('d.m.Y H\hi:s',$log_up['up_time']);
						
							if($log_up['up_id'])	
								$log_up['type'] = '<font color=green><b>Up tự động</b></font>';
							else	
								$log_up['type'] = 'Thành viên up';
								
							$arr= explode(' ',$log_up['run_order']);
							
							$log_up['run_order'] = $arr[0];
								
							if($log_up['status']==0)		
								$log_up['status'] = '<font color="orange">Chưa kích hoạt</font>';
							elseif ($log_up['status']==1)
								$log_up['status'] = '<font color="green">Hoạt động</font>';		
							elseif ($log_up['status']==2)
								$log_up['status'] = '<font color="brown">Hết lượt up</font>';		
							elseif ($log_up['status']==3)
								$log_up['status'] = '<span title="Tạm ngừng do tin bị xoá hoặc kiểm duyệt"><font color="red">Tạm ngừng</font></span>';		
								
							$log_up['del_link']  = Url::build_current(array('cmd'=>'del_log','log_id'=>$log_up['id']));
							
							$log_up['href'] 		= '?page=item_detail&id='.$log_up['item_id'];
							$log_up['item_c_time'] = '';
							$log_up['item_up_time'] = '';
		
							$log_ups[]=$log_up;
						}
					}
					
					if($log_ups){
						$display->add('item_id',$item['id']);
						$display->add('item_name',$item['name']);
						
						$display->add('post_time',date('H\hi d.m.Y',$item['created_time']));
						$display->add('up_time',date('H\hi d.m.Y',$item['up_time']));
						
						$display->add('item_url',Url::build('item_detail',array('id'=>$item['id'],'ebname'=>AZLib::safe_title($item['name']))));
						$display->add('log_ups',$log_ups);
						$display->output('UpTinLog',false,'Personal');
						System::halt();					
					}
				}
			}
		}
		
		echo 'no_log';
		exit();	 	 
	}
	
	function show_mes_inbox(){
	
		$search_text 	= AZLib::getParam('search_text');
		$is_archive 	= Url::get('is_archive',0);
		$table_topics 	= 'message_topics';
		$table_text 	= 'message_text';
		$url_cmd 		= '';
		
		$url_archive= '';
		if($is_archive){
			$table_topics = $table_topics.'_archive';
			$table_text = $table_text.'_archive';
			$url_cmd = '?cmd=archive';
			$url_archive = '&is_archive=1';
		}
		
		$condition = "mt.mt_owner_id =" .User::id() . " AND mt.mt_vid_folder = 'inbox' AND mt.mt_newest = 0";
		
		if($search_text && $search_text!="Account thành viên"){
			$condition .= " AND mt.mt_to_name LIKE '%$search_text%' ";
		}
	
		$str_content = '<form name="message">
						<div id="boxFunctions">
							Chọn: 
							<a style="cursor:pointer" id="select_all">Tất cả</a>,
							<a style="cursor:pointer" id="select_read">Đã đọc</a>,
							<a style="cursor:pointer" id="select_unchecked">Không chọn</a>
							<div id="boxFunctionRight">
								<div id="btn_del_mess" align="center" class="btnAllNewFeedback" onmouseout="this.className=\'btnAllNewFeedback\'"  onmouseover="this.className=\'btnAllNewFeedbackHover\'"  style="width:40px;">
									<div class="btnRightAllFeedback" align="center" style="width:40px"><a title="Xóa tất cả tin nhặn đã chọn" href="javascript:void(0)" onClick="return delMessage(0,\'true\',\'inbox\')">Xoá</a></div>
								</div>
							</div>
						</div>
						';
		$str_content .= '<table cellpadding="3" cellspacing="0" border="0" width="100%" id="inboxTable">';
		
		$sql_count 	= "SELECT COUNT(*) AS total_row FROM $table_topics AS mt WHERE $condition";
		//echo $sql_count;
		$total_item=DB::fetch($sql_count,'total_row',0);		
		
		$item_per_page = 15;
		$limit ='';
		$divID = 'mess_content';
		$url_path = WEB_DIR.'ajax.php?act=personal&code=show_mes_inbox'.$url_archive.'&search_text='.$search_text;
		
		$paging = AZPagging::AjaxPaging($limit,$total_item,$item_per_page,5,'page_mes','',false,false,$url_path,$divID,true);	
		
		// Lấy tin nhắn
		$sql = "SELECT msg.msg_id, msg.msg_author_name, msg.msg_date, msg.msg_post, mt.mt_id,mt.mt_ref_id, 
				mt.mt_title, mt.mt_from_id, mt.mt_owner_id, mt.mt_owner_name, mt.mt_to_name, mt.mt_read, a.avatar_url, a.img_server 
				FROM $table_text AS msg, $table_topics AS mt, user AS a
				WHERE msg.msg_id  = mt.mt_msg_id AND mt.mt_from_id = a.id AND $condition 
				ORDER BY  mt.mt_read ASC, msg.msg_date DESC $limit";
		//echo $sql;
		$result = DB::query($sql);
		$comeFrom = Url::get('ref');
		if(($comeFrom == 'top'))
		{
			$countUnread = DB::count("$table_topics` AS `mt",$condition . ' AND mt_read = 0');
			if($countUnread == 1)
			{
				$reOneRow = DB::select("$table_topics` AS `mt",$condition . ' AND mt_read = 0');
				if($reOneRow['mt_ref_id']){
					echo $reOneRow['mt_ref_id'];
				}
				else{
					echo $reOneRow['mt_id'];
				}
				exit;
			}
		}
		$stt=0;	
		
		if($result){
			while ($row=mysql_fetch_assoc($result)){						
			if($stt<$item_per_page){	
				if($row['mt_ref_id'])
				{
					$sourceTitle = DB::select($table_topics,'mt_id = ' . $row['mt_ref_id']);
					
					if($sourceTitle['mt_title']){
						$row['mt_title'] = $sourceTitle['mt_title'];
					}
					//else
					//{
					//	$sentTitle = DB::select($table_topics,'mt_mgsid = ' . $row['mt_ref_id']);
					//}
					
					$row["mt_id"] = $row['mt_ref_id'];
					$row['mt_ref_id'] = 0;
				}
				if($row['avatar_url']){
					$row['avatar_url'] = AZLib::getImageThumb($row['avatar_url'],50,50,0,$row['img_server']);
				}
				else{
					$row['avatar_url'] = "style/images/50x50.gif";
				}
				
				//$row['msg_date'] = AZLib::duration_time($row['msg_date']);
							
				$msg_date = date('H:i | ',$row['msg_date']);
				if(date('d.m.y',$row['msg_date']) == date('d.m.y',TIME_NOW)){
					$msg_date.= '<font color="green">H&#244;m nay</font>';
				}
				else{
					$msg_date.= date('d.m.y',$row['msg_date']);										
				}
				
				$row['msg_date'] = $msg_date;
				
				//$row['msg_post'] =  AZLib::convert_one_br($row['msg_post']);
				//$row['msg_post'] =  AZLib::plainText(AZLib::parseBBCode(stripslashes($row['msg_post'])));		
				
				$row['msg_post'] = preg_replace( "/\n/", "<br />", $row['msg_post']);
				$row['msg_post'] = strip_tags(AZLib::parseBBCode(AZLib::convert_one_br($row['msg_post'])),'<br />');
				
				if(strlen($row['msg_post'])>40){
					$row['msg_post_short'] = AZLib::word_limit($row['msg_post'],40,' ...');
					//$row['msg_post_short'] = AZLib::cleanHtml(AZLib::word_limit($row['msg_post'],40,' ...'));
				}
				else{
					$row['msg_post_short'] = $row['msg_post'];
					//$row['msg_post_short'] = AZLib::cleanHtml($row['msg_post']);
				}
				
				if($row["mt_read"]==0 && !$is_archive){
					$str_title = '<a onclick="detail_reload_jcache = true;fn_show_mes_detail('.$row["mt_id"].',0,\'inbox\')" rel="history" id="a_'.$row["mt_id"].'" href="message.html'.$url_cmd.'#inbox/'.$row["mt_id"].'" title="Hiển thị chi tiết" ><b>'.$row["mt_title"].'</b></a>';
					$read_class = ' unreadMessage';
				}
				else{
					$str_title = '<a onclick="detail_reload_jcache = true;fn_show_mes_detail('.$row["mt_id"].',1,\'inbox\')" rel="history" id="a_'.$row["mt_id"].'" href="message.html'.$url_cmd.'#inbox/'.$row["mt_id"].'" title="Hiển thị chi tiết">'.$row["mt_title"].'</a>';	
					$read_class = '';
				}
				
				if($row['mt_owner_id'] != User::id()){
					$strUser = '<a href="'.$row["mt_owner_name"].'">'.$row["mt_owner_name"].'</a>';
				}
				else{
					$strUser = '<a href="'.$row["mt_to_name"].'">'.$row["mt_to_name"].'</a>';
				}
				
				$str_content .= '<tr id="'.$row["mt_id"].'">
									<td align="center" class="listMessage' . $read_class . '"><input type="checkbox" class="rowbox' . $read_class . '" id="inbox_'.$row["mt_id"].'" name="inbox[]" value="'.$row["mt_id"].'"></td>
									<td align="center" class="listMessage' . $read_class . '">
										<a href="'.$row["msg_author_name"].'"><img src="'.$row["avatar_url"].'"/></a>
									</td>
									<td valign="top" class="listMessage' . $read_class . '" style="white-space:nowrap; padding-right:15px; vertical-align:middle;">
										<div>' . $strUser . '</div>
										<div class="textMestime">'.$row['msg_date'].'</div>
									</td>
									<td valign="top" class="listMessage clickable' . $read_class . '" style="padding-right:15px;width:65%;" lang="' . $row["mt_id"] . '">
										<div style="margin-top:6px;">'.$str_title.'</div>
										<div style="margin:6px 0;color:#808080">'.$row['msg_post_short'].'</div>
									</td>
									<td align="center" class="listMessage' . $read_class . '" style="padding-right:10px;"> <span><a title="Xóa tin nhắn" onClick="delMessage('.$row["mt_id"].',\'false\',\'inbox\')" href="javascript:void(0)" style="padding:20px;" class="deleteButton"> &nbsp;</a></span></td>
								</tr>
								';
				}
				
				$stt++;	
			}
					
		}		
		
		if($stt>0){
			
			$str_content .= '<tr><td></td><td>
								
								</td><td colspan="2"><div style="float:right">'.$paging.'</div><div style="clear:right"></div></td></tr>';
		}
		else{
			$str_content .= '<tr><td></td><td colspan="3">
								<center><div class="noMess">Không có Tin nhắn nào trong hộp tin nhắn</div></center>
								</td></tr>';
		}
									
		$str_content .= '</table></form>
			
		';	
			
		echo $str_content;
		exit();				
		
	}
	
	function show_mes_outbox(){
	
		$search_text = AZLib::getParam('search_text');
		$is_archive = Url::get('is_archive',0);
		$table_topics = 'message_topics';
		$table_text = 'message_text';
		$url_archive = '';
		$url_cmd = '';
		if($is_archive){
			$table_topics = $table_topics.'_archive';
			$table_text = $table_text.'_archive';
			$url_cmd = '?cmd=archive';
			$url_archive = '&is_archive=1';
		}
		$condition = $table_topics.'.mt_owner_id ='.User::id().' 
					AND '.$table_topics.'.mt_vid_folder = "sent" 
					AND '.$table_topics.'.mt_newest = 0';
		
		if($search_text && $search_text!="Account thành viên"){
			$condition .= " AND mt_to_name LIKE '%$search_text%' ";
		}
	
	
		$str_content = '<form name="message">
						<div id="boxFunctions">
							Chọn: 
							<a style="cursor:pointer" id="select_all">Tất cả</a>,
							<a style="cursor:pointer" id="select_read">Đã đọc</a>,
							<a style="cursor:pointer" id="select_unchecked">Không chọn</a>
							<div id="boxFunctionRight">
								<div id="btn_del_mess" align="center" class="btnAllNewFeedback" onmouseout="this.className=\'btnAllNewFeedback\'"  onmouseover="this.className=\'btnAllNewFeedbackHover\'"  style="width:40px;">
									<div class="btnRightAllFeedback" align="center" style="width:40px"><a title="Xóa tất cả tin nhặn đã chọn" href="javascript:void(0)" onClick="return delMessage(0,\'true\',\'outbox\')">Xoá</a></div>
								</div>
							</div>
						</div>
						
						';
		$str_content .= '<table cellpadding="3" cellspacing="0" border="0" width="100%">';
		
		$sql_count = 'SELECT COUNT(mt_id) AS total_row FROM '.$table_topics.' WHERE '.$condition;
						
		$total_item=DB::fetch($sql_count,'total_row',0);	
		
		$item_per_page = 15;
		$limit ='';
		$divID = 'mess_content';
		$url_path = WEB_DIR.'ajax.php?act=personal&code=show_mes_outbox'.$url_archive.'&search_text='.$search_text;
		
		$paging = AZPagging::AjaxPaging($limit,$total_item,$item_per_page,5,'page_mes','',false,false,$url_path,$divID,true);	
				
		$sql = 'SELECT '.$table_text.'.msg_id,	'.$table_text.'.msg_author_name, '.$table_text.'.msg_date, '.$table_text.'.msg_post, '.$table_topics.'.mt_id, '.$table_topics.'.mt_ref_id, 
					'.$table_topics.'.mt_title, '.$table_topics.'.mt_from_id, '.$table_topics.'.mt_owner_id, '.$table_topics.'.mt_read, ' .$table_topics.'.mt_owner_name, '.$table_topics.'.mt_to_name, 
					user.avatar_url, user.img_server 
				FROM '.$table_text.', '.$table_topics.', user 
				WHERE '.$table_text.'.msg_id  = '.$table_topics.'.mt_msg_id AND '.$table_topics.'.mt_from_id = user.id AND '.$condition.' 
				ORDER BY '.$table_text.'.msg_date DESC '.$limit;
		//echo $sql;
		//exit;
		$result = DB::query($sql);
		
		$stt=0;	
		
		if($result){
			while ($row=mysql_fetch_assoc($result)){						
			if($stt<$item_per_page){	
				if($row['mt_ref_id']){
					$sourceTitle = DB::select($table_topics,'mt_id = ' . $row['mt_ref_id']);
					if($sourceTitle['mt_title'])
					{
						$row['mt_title'] = $sourceTitle['mt_title'];
					}
					//else
					//{
					//	$sentTitle = DB::select($table_topics,'mt_mgsid = ' . $row['mt_ref_id']);
					//}
					$row["mt_id"] = $row['mt_ref_id'];
					$row['mt_ref_id'] = 0;
				}
				
				if($row['avatar_url']){
					$row['avatar_url'] = AZLib::getImageThumb($row['avatar_url'],50,50,0,$row['img_server']);
				}
				else{
					$row['avatar_url'] = "style/images/50x50.gif";				
				}
				//$row['msg_date'] = AZLib::duration_time($row['msg_date']);
				
				$msg_date = date('H:i | ',$row['msg_date']);
				if(date('d.m.y',$row['msg_date']) == date('d.m.y',TIME_NOW)){
					$msg_date.= '<font color="green">H&#244;m nay</font>';
				}
				else{
					$msg_date.= date('d.m.y',$row['msg_date']);										
				}
				
				$row['msg_date'] = $msg_date;	
				
				$row['msg_post'] = preg_replace( "/\n/", "<br />", $row['msg_post']);
				$row['msg_post'] = strip_tags(AZLib::parseBBCode(AZLib::convert_one_br($row['msg_post'])),'<br />');
				
				if(strlen($row['msg_post'])>40){
					$row['msg_post_short'] = AZLib::word_limit($row['msg_post'],40,' ...');
					//$row['msg_post_short'] = AZLib::cleanHtml(AZLib::word_limit($row['msg_post'],40,' ...'));
				}
				else{
					$row['msg_post_short'] = $row['msg_post'];
					//$row['msg_post_short'] = AZLib::cleanHtml($row['msg_post']);
				}
				
				//$str_title = '<a onclick="fn_show_mes_detail('.$row["mt_id"].')" rel="history" href="message.html'.$url_cmd.'#outbox/'.$row["mt_id"].'" id="a_'.$row["mt_id"].'" title="Hiển thị chi tiết" >'.$row["mt_title"].'</a> - <span class="textMestime">'.$row['msg_date'].'</span>';	
				
				if($row['mt_owner_id'] != User::id())
				{
					$strUser = '<a href="'.$row["mt_owner_name"].'">'.$row["mt_owner_name"].'</a>';
				}
				else
				{
					$strUser = '<a href="'.$row["mt_to_name"].'">'.$row["mt_to_name"].'</a>';
				}
				
				if($row["mt_read"]==0 && !$is_archive){
					$str_title = '<a onclick="detail_reload_jcache = true;fn_show_mes_detail('.$row["mt_id"].',1,\'outbox\')" rel="history" id="a_'.$row["mt_id"].'" href="message.html'.$url_cmd.'#outbox/'.$row["mt_id"].'" title="Hiển thị chi tiết" ><b>'.$row["mt_title"].'</b></a>';
					$read_class = ' unreadMessage';
				}
				else{
					$str_title = '<a onclick="detail_reload_jcache = true;fn_show_mes_detail('.$row["mt_id"].',1,\'outbox\')" rel="history" id="a_'.$row["mt_id"].'" href="message.html'.$url_cmd.'#outbox/'.$row["mt_id"].'" title="Hiển thị chi tiết">'.$row["mt_title"].'</a>';	
					$read_class = '';
				}
				
				$str_content .= '<tr id="'.$row["mt_id"].'">
									<td align="center" class="listMessage' . $read_class . '"><input type="checkbox" class="rowbox' . $read_class . '" id="inbox_'.$row["mt_id"].'" name="inbox[]" value="'.$row["mt_id"].'"></td>
									<td align="center" class="listMessage' . $read_class . '">
										<a href="'.$row["msg_author_name"].'"><img src="'.$row["avatar_url"].'"/></a>
									</td>
									<td valign="top" class="listMessage' . $read_class . '" style="white-space:nowrap; padding-right:15px; vertical-align:middle;">
										<div>' . $strUser . '</div>
										<div class="textMestime">'.$row['msg_date'].'</div>
									</td>
									<td valign="top" class="listMessage clickable' . $read_class . '" style="padding-right:15px;width:65%;" lang="' . $row["mt_id"] . '">
										<div style="margin-top:6px;">'.$str_title.'</div>
										<div style="margin:6px 0;color:#808080">'.$row['msg_post_short'].'</div>
									</td>
									<td align="center" class="listMessage' . $read_class . '" style="padding-right:10px;"> <span><a title="Xóa tin nhắn" onClick="return delMessage('.$row["mt_id"].',\'false\',\'inbox\')" href="javascript:void(0)" style="padding:20px;" class="deleteButton"> &nbsp;</a></span></td>
								</tr>
								';
				
				/*$str_content .= '<tr id="'.$row["mt_id"].'">
									<td align="center" class="listMessage' . $read_class . '"><input type="checkbox" id="inbox_'.$row["mt_id"].'" name="inbox[]" value="'.$row["mt_id"].'"></td>
									<td align="center" class="listMessage' . $read_class . '">
										<a href="'.$row["mt_to_name"].'"><img src="'.$row["avatar_url"].'"  vspace="4" hspace="4"/></a>
										<div><a href="'.$row["mt_to_name"].'">'.$row["mt_to_name"].'</a></div>	
									</td>
									<td valign="top" style="width:65%;" class="listMessage' . $read_class . '">
										<div>'.$str_title.'</div>
										<div style="margin-top:6px">'.$row['msg_post_short'].'</div>
									</td>
									<td align="center" class="listMessage' . $read_class . '"> <span><a title="Xóa tin nhắn" onClick="delMessage('.$row["mt_id"].',\'false\',\'sent\')" href="javascript:void(0)"> <img src="style/images/icon_delete.gif" width="9" height="9" /></a></span></td>
								</tr>';*/
				}
				$stt++;	
			}
					
		}		
		
		if($stt>0){
			
			$str_content .= '<tr><td></td><td>
								</td><td colspan="2"><div style="float:right">'.$paging.'</div><div style="clear:right"></div></td></tr>';
		}
		else{
			$str_content .= '<tr><td></td><td colspan="3">
								<center><div class="noMess">Không có Tin nhắn nào trong tin đã gửi</div></center>
								</td></tr>';
		}
									
		$str_content .= '</table></form>';
			
		echo $str_content;
		exit();				
		
	}
	
	function delmess(){
		
		if(!User::is_login()){
			echo 'no_login';	
			exit;
		}
		
		$mt_id = (int)Url::get("mt_id","");	
		$mt_ids = Url::get("mt_ids","");
	
		
		$is_archive = Url::get('is_archive',0);
		$table_topics = 'message_topics';
		$table_text = 'message_text';
		$url_cmd = '';
		$url_archive= '';
		if($is_archive){
			$table_topics = $table_topics.'_archive';
			$table_text = $table_text.'_archive';
			$url_cmd = '?cmd=archive';
			$url_archive = '&is_archive=1';
		}
		
		if($mt_id>0){// xoa 1 item
			$sql_item = 'SELECT	mt_read, mt_msg_id, mt_owner_id, msg_sent_to_count, msg_deleted_count FROM '.$table_text.', '.$table_topics.' WHERE '.$table_text.'.msg_id  = '.$table_topics.'.mt_msg_id AND '.$table_topics.'.mt_id = '.$mt_id;
			$result = DB::query($sql_item);
	
			if($result){
				$reCountPm = false; // = true nếu tin gốc chưa được đọc hoặc một trong những tin trả lời của luồng tin hiện tại chưa được đọc
									
				$countUnread = DB::count($table_topics,'mt_owner_id = ' . User::id() . ' AND mt_ref_id = ' . $mt_id . ' AND mt_read = 0');
				
				if($countUnread)
				{
					$reCountPm = true;
				}
				
				// Lấy danh sách message_text.msg_id của những trả lời trong luồng tin nhắn hiện tại
				$reText = DB::query('SELECT DISTINCT GROUP_CONCAT('.$table_text.'.msg_id) AS msg_id
									FROM '.$table_text.' RIGHT JOIN '.$table_topics.' ON ('.$table_text.'.`msg_id` = ' . $table_topics . '.`mt_msg_id`)
									WHERE ' . $table_topics . '.mt_owner_id = ' . User::id() . ' 
										AND ' . $table_topics . '.mt_ref_id = ' . $mt_id);
				//AND ' . $table_topics . '.mt_vid_folder = \'inbox\'
				if($reText)
				{
					$rowText = mysql_fetch_assoc($reText);
					$listTextIDs = $rowText['msg_id'];
				}
				else
				{
					$listTextIDs = '';
				}
				
				if($listTextIDs)
				{
					// Kiểm tra xem những message_text của các tin nhắn trả lời đã xóa
					$reText = DB::query('SELECT DISTINCT GROUP_CONCAT('.$table_text.'.msg_id) AS msg_id
										FROM '.$table_text.' RIGHT JOIN '.$table_topics.' ON ('.$table_text.'.`msg_id` = '.$table_topics.'.`mt_msg_id`)
										WHERE '.$table_text.'.msg_id IN(' . $listTextIDs . ')
											AND '.$table_topics.'.mt_owner_id <> ' . User::id());
					if($reText)
					{
						$rowText = mysql_fetch_assoc($reText);
						$listNotInTextIDs = $rowText['msg_id'];
					}
					else
					{
						$listNotInTextIDs  = '';
					}
					// Nếu những message_text mà không còn message_topics nào thì xóa message_text đi			
					$sql = 'DELETE FROM '.$table_text.' WHERE msg_id IN(' . $listTextIDs . ')';
					if($listNotInTextIDs)
					{
						$sql .= ' AND msg_id NOT IN (' . $listNotInTextIDs . ')';
					}
					DB::query($sql);
				}
				
				// Xóa những tiêu đề của tin nhắn trả lời
				DB::query('DELETE FROM '.$table_topics.'
							WHERE '.$table_topics.'.mt_owner_id = ' . User::id() . ' 
								AND '.$table_topics.'.mt_ref_id = ' . $mt_id);
				//AND '.$table_topics.'.mt_vid_folder = \'inbox\'
				$row = mysql_fetch_assoc($result);
				
				// Nếu là tin nhắn chưa đọc, cập nhật lại tổng số tin nhắn của user hiện tại
				if(($row["mt_read"]==0)||$reCountPm){ // cap nhat lai tong so pm
					DB::query("UPDATE user SET total_pm  = total_pm-1 WHERE id = ".User::id()." AND total_pm>0");
					User::getUser(User::id(),1,0);
				}
				if($row["mt_owner_id"]==User::id()){	
					$mt_msg_id = $row["mt_msg_id"];
					
					// Xóa tin nhắn gốc của luồng tin
					DB::query("DELETE FROM $table_topics WHERE mt_id=$mt_id");// xoa tin nhan
					$msg_deleted_count = $row["msg_deleted_count"]+1;
					$msg_sent_to_count = $row["msg_sent_to_count"];
					DB::query("UPDATE $table_text SET msg_deleted_count = $msg_deleted_count WHERE msg_id = $mt_msg_id");
					
					if($msg_sent_to_count==$msg_deleted_count){
						DB::query("DELETE FROM $table_text WHERE msg_id = $mt_msg_id");
					}
					echo "success";
					exit();
				}
				/*else{
					echo "unsuccess";
					exit();
				}*/
			}
			else{
				echo "unsuccess";
				exit();
			}
		}
		elseif($mt_ids!=""){ // xoa nhieu items
			$sql_item = 'SELECT	mt_id, mt_read, mt_msg_id, mt_owner_id, msg_sent_to_count, msg_deleted_count FROM '.$table_text.', '.$table_topics.' WHERE '.$table_text.'.msg_id  = '.$table_topics.'.mt_msg_id AND '.$table_topics.'.mt_id IN('.$mt_ids.')';
			$result = DB::query($sql_item);
			if($result){
				while($row = mysql_fetch_assoc($result)){
					// Lấy danh sách message_text.msg_id của những trả lời trong luồng tin nhắn hiện tại
					$reText = DB::query('SELECT DISTINCT GROUP_CONCAT('.$table_text.'.msg_id) AS msg_id
										FROM '.$table_text.' RIGHT JOIN '.$table_topics.' ON ('.$table_text.'.`msg_id` = ' . $table_topics . '.`mt_msg_id`)
										WHERE ' . $table_topics . '.mt_owner_id = ' . User::id() . ' 
											AND ' . $table_topics . '.mt_vid_folder = \'inbox\'
											AND ' . $table_topics . '.mt_ref_id = ' . $row["mt_id"]);
					
					if($reText)
					{
						$rowText = mysql_fetch_assoc($reText);
						$listTextIDs = $rowText['msg_id'];
					}
					else
					{
						$listTextIDs = '';
					}
					
					if($listTextIDs)
					{
						// Kiểm tra xem những message_text của các tin nhắn trả lời đã xóa
						$reText = DB::query('SELECT DISTINCT GROUP_CONCAT('.$table_text.'.msg_id) AS msg_id
											FROM '.$table_text.' RIGHT JOIN '.$table_topics.' ON ('.$table_text.'.`msg_id` = '.$table_topics.'.`mt_msg_id`)
											WHERE '.$table_text.'.msg_id IN(' . $listTextIDs . ')
												AND '.$table_topics.'.mt_owner_id <> ' . User::id());
						if($reText)
						{
							$rowText = mysql_fetch_assoc($reText);
							$listNotInTextIDs = $rowText['msg_id'];
						}
						else
						{
							$listNotInTextIDs  = '';
						}
					
						// Nếu những message_text mà không còn message_topics nào thì xóa message_text đi			
						$sql = 'DELETE FROM '.$table_text.' WHERE msg_id IN(' . $listTextIDs . ')';
						if($listNotInTextIDs)
						{
							$sql .= ' AND msg_id NOT IN (' . $listNotInTextIDs . ')';
						}
						DB::query($sql);
					}
					
					// Xóa những tiêu đề của tin nhắn trả lời
					DB::query('DELETE FROM '.$table_topics.'
							WHERE '.$table_topics.'.mt_owner_id = ' . User::id() . ' 
								AND '.$table_topics.'.mt_vid_folder = \'inbox\'
								AND '.$table_topics.'.mt_ref_id = ' . $row["mt_id"]);
				
					if($row["mt_owner_id"]==User::id()){
						//if($row["mt_read"]==0){ // cap nhat lai tong so pm
						//	DB::query("UPDATE user SET total_pm  = total_pm-1 WHERE id = ".User::id()." AND total_pm>0");
						//}
						
						$mt_msg_id = $row["mt_msg_id"];
						DB::query("DELETE FROM $table_topics WHERE mt_id=".$row["mt_id"]);// xoa tin nhan
						$msg_deleted_count = $row["msg_deleted_count"]+1;
						$msg_sent_to_count = $row["msg_sent_to_count"];
						DB::query("UPDATE $table_text SET msg_deleted_count = msg_deleted_count+1 WHERE msg_id = $mt_msg_id");
						
						if($msg_deleted_count==$msg_sent_to_count){
							DB::query("DELETE FROM $table_text WHERE msg_id = $mt_msg_id");
						}
					}
					
					$condition = 'mt_owner_id =' .User::id() . ' AND mt_vid_folder = "inbox" AND mt_read = 0';
					$rows_total = DB::count('message_topics',$condition);
					DB::query("UPDATE user SET total_pm  = " . $rows_total . " WHERE id = ".User::id());
				}
				User::getUser(User::id(),1,0);
				echo "success";
				exit();
			}
			else{
				echo "unsuccess";
				exit();
			}
		}
		else{
			echo "unsuccess";
			exit();
		}
	}
	
	function send_mess(){
		if(!User::is_login()){
			echo 'no_login';	
			exit;
		}
		
		$is_save = (int)Url::get("is_save",0);	
		$user_name = trim(Url::get("user_name",""));
		$ref_id = (int)Url::get('ref_id',0);
		$title_pm = trim(Url::get("title_pm",""));	
		$content_pm = trim(Url::get("content_pm",""));
		
		if($user_name==User::user_name()){
			echo "your_self";
			exit();
		}
		
		if($title_pm=="" || $content_pm==""){
			echo "unsuccess";
			exit();
		}
		
		if($user_name && $title_pm && $content_pm){
					
			$user_name = trim($user_name,",");
			$user_name = preg_replace("/,,/", "", $user_name);
				
			$arr_user = explode(",",$user_name);
			
			if(User::have_permit(SEND_MORE_MESSAGE))
			{
				$limit_user = 200;
			}
			else
			{
				$limit_user = 5;
			}
			
			if(count($arr_user)>$limit_user){
				echo "over_limit";
				exit();
			}
			
			if(count($arr_user)==0){
				echo "unsuccess";
				exit();
			}
			
			$str_return = "";
			
			for ($i=0; $i<count($arr_user) && $i<$limit_user; $i++){
				
				$username_explode = trim($arr_user[$i]);
				
				$sql = "SELECT id FROM user WHERE user_name='$username_explode'";			
				$result = DB::query($sql);
				$row = mysql_fetch_assoc($result);
				
				if($row["id"]>0){
				
					if($row["id"]==User::id()){
						$str_return .="<div>Tài khoản $username_explode là của bạn nên không gửi được</div>";
					}
					else{
						$user_receiver = User::getUser($row["id"]);
						$id_pm = AZLib::Send_pm(User::id(),User::user_name(),$user_receiver,$title_pm,$content_pm,!$is_save,$ref_id);
						if($id_pm){
							User::getUser($row["id"],1,0);
							$str_return .="<div>Gửi tin nhắn tới $username_explode thành công</div>";
							
						}
					}			
				}
				else{
					$str_return .="<div>Tài khoản $username_explode không tồn tại</div>";
				}						
			}	
			echo $str_return;
			exit();					
		}
		else{
			echo "unsuccess";
			exit();
		}
	}	
	
	function fwrpMess(){
	
		$json 		= "";
		
		if(!User::is_login()){
			$json = '({"msg":"no_login"})';
			echo $json;
			//echo 'no_login';
			exit;
		}
		
		$mt_id = (int)Url::get("mt_id");
		$code   = Url::get("code","");
		
		$is_archive = Url::get('is_archive',0);
		$table_topics = 'message_topics';
		$table_text = 'message_text';
		$url_cmd = '';
		$url_archive= '';
		if($is_archive){
			$table_topics = $table_topics.'_archive';
			$table_text = $table_text.'_archive';
			$url_cmd = '?cmd=archive';
			$url_archive = '&is_archive=1';
		}
		
		if($mt_id>0){
			$sql_item = 'SELECT	mt_to_name, msg_post, msg_author_name, mt_title, mt_owner_id,mt_owner_name FROM '.$table_text.', '.$table_topics.'	WHERE '.$table_text.'.msg_id  = '.$table_topics.'.mt_msg_id AND '.$table_topics.'.mt_id = '.$mt_id;
			$result = DB::query($sql_item);
			if($result){
				$row = mysql_fetch_assoc($result);
				
				$title = AZLib::plainText($row["mt_title"]);					
				$title = preg_replace("/\'|\"/is", "`", $title);
				
				$content = $row["msg_post"];
				$receiver = $row["mt_to_name"];
				
				$content = str_replace("{","\{",$content);
				$content = str_replace("}","\}",$content);
				$content = str_replace("[","\[",$content);
				$content = str_replace("]","\]",$content);				
				$content = preg_replace("/\'|\"/is", "`", $content);
				
				$content = str_replace(array(chr(13),chr(10)),'\n',$content);			
				
				if($code=="fwMess"){
					//$title_line = '[b]Chuyển tiếp từ '.$row["mt_to_name"].'[/b]';
					$title_line = '[b]Chuyển tiếp từ '.$row["msg_author_name"].'[/b]';
					$title = "FW: ".$title;
					$receiver = "";
					$title_line .= '\n';
					$content = "[quote]".$title_line.'[i]'.$content.'[/i]'.'[/quote]';
				}
				elseif($code=="rpMess"){
					//$title_line = '[b]Phản hồi từ '.$row["mt_owner_name"].'[/b]';
					//$title_line .= '\n';
					$title = "Re: ".$title;
					//$content = "[quote]".$title_line.'[i]'.$content.'[/i]'.'[/quote]';
				}
				
				if($row["mt_owner_id"]==User::id()){
					$json = '({"msg":"success"';
					$json .= ',"receiver":"'.$receiver.'"';		
					$json .= ',"title":"'.$title.'"';						
					$json .= ',"ref_id":"'.$mt_id.'"';
					$json .= ',"content":"'.$content.'"';	
					
										
					$json.='})';
					
					echo $json;
					//echo 'success,'.$receiver.','.$title.','.$content;
					exit;
				}
				else{
					$json = '({"msg":"unsuccess"})';
					echo $json;
					//echo 'unsuccess';
					exit;
				}	
			}
		}
		else{
			$json = '({"msg":"unsuccess"})';
			echo $json;
			//echo 'unsuccess';
			exit;
		}
	}
	
	function change_password(){

	$json 		= "";	
	if(!User::is_login()){
		$json = '({"msg":"no_login"})';
		echo $json;
		exit;
	}

	$old_password = Url::get("old_password","");
	$new_password = Url::get("new_password","");
	$retype_new_password = Url::get("retype_new_password","");
	
	if($new_password==$retype_new_password){
		if(DB::update('user',array('password'=>User::encode_password($new_password)),'id='.User::id())){
			$json = '({"msg":"success"';
			$json .= ',"note":"Thay đổi mật khẩu thành công"';									
			$json.='})';				
			echo $json;
			exit;
		}
		else{
			$json = '({"msg":"unsuccess"';
			$json .= ',"note":"Có lỗi xẩy ra. Không thay đổi được mật khẩu"';									
			$json.='})';				
			echo $json;
			exit;
		}
		
	}
	else{
		$json = '({"msg":"unsuccess"';
		$json .= ',"note":"Xác nhận mật khẩu không đúng"';									
		$json.='})';				
		echo $json;
		exit;		
	}
	
}

//add by nhatvt
    function filter_link($link,$text){
		if($text=AZLib::trimSpace(AZLib::plainText($text))){
			$text=AZLib::strippedLink($text);
			if(strpos($link,'http://enbac.com')===0 || strpos($link,'http://www.enbac.com')===0 || strpos($link,'enbac.com')===0 || strpos($link,'http://')===false){
				return "<a href=\"$link\" target=\"_blank\">$text</a>";
			}else if(strpos($link,'http://blog.enbac.com')===0 || strpos($link,'blog.enbac.com')===0 || strpos($link,'http://')===false){
                return "<a href=\"$link\" target=\"_blank\">$text</a>";
            }else if(strpos($link,'http://help.enbac.com')===0 || strpos($link,'help.enbac.com')===0 || strpos($link,'http://')===false){
                return "<a href=\"$link\" target=\"_blank\">$text</a>";
            }
			return "<a href=\"#\" rel=\"nofollow\" target=\"_blank\">...</a>";
		}
		return '';
	}

    function process_description($content)
	{
        $content = preg_replace('/<a[\s]*(.*)[\s]*href=[\'"](.*)[\'"][\s]*[^>]*[\s]*>(.*)<\/a>/eisU', "\$this->filter_link('$2','$3')", $content);

        return $content;
	}
}//class
?>